I have divs that I want to highlight with CSS with an onClick
.
<div
className={"amount-circle" + (this.state.activeCircle ? ' active' : '')}
onClick={() => this.amountChanged(2)}>
<p>2</p>
</div>
<div
className={"amount-circle" + (this.state.activeCircle ? ' active' : '')}
onClick={() => this.amountChanged(5)}>
<p>5</p>
</div>
<div
className={"amount-circle" + (this.state.activeCircle ? ' active' : '')}
onClick={() => this.amountChanged(10)}>
<p>10</p>
</div>
My state activeCircle
is a boolean which is set to false
at the beginning.
In this.amountChanged()
I set activeCircle
to true.
But the problem is, that every div is highlighted onClick
and I did not figure out how to do it without a key
.
I have divs that I want to highlight with CSS with an onClick
.
<div
className={"amount-circle" + (this.state.activeCircle ? ' active' : '')}
onClick={() => this.amountChanged(2)}>
<p>2</p>
</div>
<div
className={"amount-circle" + (this.state.activeCircle ? ' active' : '')}
onClick={() => this.amountChanged(5)}>
<p>5</p>
</div>
<div
className={"amount-circle" + (this.state.activeCircle ? ' active' : '')}
onClick={() => this.amountChanged(10)}>
<p>10</p>
</div>
My state activeCircle
is a boolean which is set to false
at the beginning.
In this.amountChanged()
I set activeCircle
to true.
But the problem is, that every div is highlighted onClick
and I did not figure out how to do it without a key
.
-
1
You need to check
this.state.amount === 2
or5
or10
based on the value that you are applying. – Zain Zafar Commented May 7, 2020 at 18:07 -
1
like this
className={"amount-circle" + (this.state.amount === 2 ? ' active' : '')}
– Zain Zafar Commented May 7, 2020 at 18:07 - I just answered similar question :- stackoverflow./a/61663988/8130690 – Lakshya Thakur Commented May 7, 2020 at 18:10
2 Answers
Reset to default 3The reason all divs bee active is because they depend on the same flag.
The most correct solution here would be to rely on the set amount
Assuming you set the selected amount in the state amount, you would implement the active logic like below
<div
className={"amount-circle" + (this.state.amount == 2 ? ' active' : '')}
onClick={() => this.amountChanged(2)}>
<p>2</p>
</div>
<div
className={"amount-circle" + (this.state.amount == 5 ? ' active' : '')}
onClick={() => this.amountChanged(5)}>
<p>5</p>
</div>
<div
className={"amount-circle" + (this.state.amount == 10 ? ' active' : '')}
onClick={() => this.amountChanged(10)}>
<p>10</p>
</div>
Can't you just do something like that ?
<div onClick={(e) => e.target.classList.toggle('active')}>
coucou
</div>
You won't depend on any flag, just the click target. Here is a repro on StackBlitz