I am trying to toggle a button with hook, classname and id but all buttons toggle color instead of one button that is actually clicked.
The classname is to toggle classname "dark" and null, where .dark changes the button black.
import './Clothing.css'
import data from '../../data/data2.json';
const Clothing = () => {
const [toggle, setToggle] = useState(null);
const types = [
{ id: 11, value: 'All' },
{ id: 22, value: 'Cap' },
{ id: 33, value: 'Sweatshirt' },
{ id: 44, value: 'Hoodie' },
{ id: 55, value: 'Shirt' }
]
const handleToggle = (e) => {
console.log(e.target.id)
if (types.filter(
(item) => item.id === e.target.id
)) return setToggle(!toggle)
}
<div className="buttonDiv">
{
types.map((t) =>
<button
key={t.id}
id={t.id}
value={t.value}
className={ toggle ? "dark" : null}
onClick={(e) => {
handleSelectedCategory(e);
handleToggle(e);
}}>
{t.value}
</button>
)
}
</div>
.clothSection {
position: absolute;
top: 25%;
width: 100%;
padding: 0 2rem;
.topMenu {
display: flex;
flex-direction: column;
padding: 2rem 4rem;
.buttonDiv {
gap: 2rem;
display: flex;
padding: 2rem 0;
button {
background-color: var(--InputColor);
padding: .5rem 1rem;
border-radius: .5rem;
font-size: var(--NormalFontSize);
color: var(--TextColor);
cursor: pointer;
border: none;
}
.dark {
background-color: var(--BlackColor);
color: var(--WhiteColor);
}
2
Answers
Hello you should use classnames like this:
It is my understanding that you have several buttons. You wish to click a button and have that button dynamically add the
.dark
class, giving each button its own independent state.The issue is that you have
toggle
andsetToggle
happening in a parent component. Then you render all of your buttons with the current value oftoggle
. We want each button to contain its owntoggle
value.New
ClothingItem.js
I added a new component
ClothingItem.js
, which is responsible for rendering a single clothing item. Notice how this component tracks and sets its owntoggle
value, utilizing most of the code you had in place to render a button initially.Updated
Clothing.js
We removed all the existing state and the
handleToggle()
function. In addition, instead of rendering<button>
s, we now render<ClothingItem />
s, passing inkey
,id
, andvalue
as before.