React is a powerful library for building dynamic user interfaces, and one of the best ways to learn it is through small, fun projects. In this blog post, I’ll walk you through a basic yet interactive component I created — a bulb toggle that turns on and off with a button click.
What You'll Learn
- How to use React
useState
for toggling UI - Conditional rendering of images
- Handling click events
The Idea
The goal is to create a bulb that changes its image based on whether it's "on" or "off", controlled by a button. This simple interaction teaches the foundation of state management and conditional rendering in React.
The Component Code
import React, { useState } from 'react';
function BulbToggle() {
const [isOn, setIsOn] = useState(false); // bulb is off initially
return (
<div>
{/* Bulb image changes based on the state */}
{isOn ? <img src="/bulb1.jpg" alt="Bulb On" /> : <img src="/bulb2.jpg" alt="Bulb Off" />}
{/* Button toggles the state */}
<button onClick={() => setIsOn(!isOn)}>
{isOn ? 'Turn Off' : 'Turn On'}
</button>
</div>
);
}
export default BulbToggle;
Image Files
Make sure to add two images in your public
folder:
-
bulb1.jpg
→ glowing bulb (for ON state) -
bulb2.jpg
→ non-glowing bulb (for OFF state)
If you’re using a React development server (like with Create React App), placing these files inside the /public
directory ensures they can be accessed via src="/bulb1.jpg"
.
How It Works
- State Initialization
const [isOn, setIsOn] = useState(false);
-
isOn
holds the current state of the bulb. - Initially set to
false
, meaning the bulb is OFF.
- Conditional Rendering
{isOn ? <img src="/bulb1.jpg" /> : <img src="/bulb2.jpg" />}
- Displays one image when
isOn
is true, and another when false.
- Button with Toggle Logic
<button onClick={() => setIsOn(!isOn)}>
- The
onClick
handler toggles theisOn
state. - Button text also updates based on the current state.
Why This Is a Great Beginner Project
This component:
- Teaches state management (
useState
) - Demonstrates conditional rendering
- Introduces user interaction
- Is visually rewarding (you see the bulb turn on and off!)
Final Thoughts
Creating interactive components like this helps you practice the core ideas behind React development. The bulb toggle is a great starting point, and you can build on it with more advanced features like:
- Sound effects
- Animations
- State persistence (e.g., localStorage)
- Dark/light mode integration
Top comments (4)
nice, these beginner projects always teach me so much. you ever feel like simple stuff like this is actually harder to outgrow than people think?
Totally agree! The basics always sneak back in—even in advanced projects. They’re harder to outgrow than people think.
Love how visual feedback like this really helps cement the basics - have you thought about taking it further with some simple CSS animations?
Thanks! That's a great idea — I’ll definitely look into adding some CSS animations to enhance it further.