Issue
I'm just trying to figure out how to toggle a css class for an individual button that is generated from a mapped array.
My code works, but it toggles every mapped button, not just the button selected.
<div className='synonym-keeper'>
{synArr.map((syn) => (
<button
className={`synonym ${isPressed && 'active'}`}
onClick={() => toggleIsPressed(!isPressed)}
>
{syn}
</button>
))}
</div>
How do I make just the selected button's css toggle?
Solution
Create another component called Togglebutton
and keep the toggle logic in it. That way you can toggle the individual button.
This would also work:
const synArr = ["button 1", "button 2", "button 3"];
const ToggleButton = ({ text }) => {
const [isPressed, toggleIsPressed] = React.useState(false);
return (
<button
className={`synonym ${isPressed && "active"}`}
onClick={() => toggleIsPressed(!isPressed)}
>
{text}
</button>
);
};
function App() {
return (
<div className="synonym-keeper">
{synArr.map((syn) => (
<ToggleButton text={syn} key={syn}/>
))}
</div>
);
}
ReactDOM.render(<App />, document.querySelector('.react'));
.synonym.active {
background-color: green;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Answered By - Amila Senadheera
Answer Checked By - - Candace Johnson (ReactFix Volunteer)