Create 3 buttons in React and highlight the clicked one with green color:
✅ Output Behavior:
- Only one button at a time should be green (clicked one).
- Others remain default.
💡 Code (with explanation):
App.js:
import './App.css';
import { useState, useEffect } from 'react';
// four btn - bt1, bt2, btn3, btn4
function App() {
const [activeBtn, setActiveBtn] = useState(null);
const handleChangeColor = (e) => {
setActiveBtn(e);
};
const buttons = ['Button1', 'Button2', 'Button3', 'Button4'];
return (
<>
<div>
{buttons.map((btn, i) => (
<button
onClick={() => handleChangeColor(i)}
className={`btnColor ${activeBtn === i ? 'clicked' : ''}`}
>
{btn}
</button>
))}
</div>
</>
);
}
export default App;
App.css:
.btnColor.clicked {
background-color: yellow;
}
📌 How It Works:
activeIndexstores the index of the clicked button.- On button click, it updates the
activeIndex. - The button’s
backgroundColoris conditionally styled based on this index.