Reputation: 439
Using react, I have a button with an icon, a font-awsome one. I want to toggle between icon on click: the icon is an eye with a title and a boolean. If the boolean is true, the eye should be open. If the same button is clicked, the boolean turns false and the button's icon should change to close. My button already has a verification so it will change the icon if the boolean is true or false, my problem is on changing the boolean onClick. Tried with setState wasnt able to do so.
My button:
{props.eyes.map(eye => {
return (<div className={"column is-2"}>
<button
className={eye.toggled === 'true' ? "button is-white fa fa-eye" : "button is-white fa fa-eye-slash"}
onClick={() => props.pickEye(eye)}/>
{eye.tituloEye}
</div>)
})}
My state:
state = {
eyes:
[
{
toggled: 'false',
tituloEye: 'porta'
},
{
toggled: 'true',
tituloEye: 'prateleira'
},
],
eyeSelecionado: '',
}
and Im getting the click button like:
pickEye = (eye) => {
this.setState({eyeSelecionado: eye});
};
Upvotes: 2
Views: 7009
Reputation: 281606
You need to set the toggled value in the parent state like
{props.eyes.map((eye, index) => {
return (<div className={"column is-2"}>
<button
className={eye.toggled === true
? "button is-white fa fa-ye"
: "button is-white fa fa-eye-slash"
}
onClick={() => props.pickEye(index)}
/>
{eye.tituloEye}
</div>
)
}
)}
pickEye = (index) => {
this.setState(prevState => ({
var newState = {
[index]: {
...prevState.eyes[index],
toggled: !prevState.eyes[index].toggled
}
};
eyes: Object.assign([], prevState.eyes, newState)}));
};
Upvotes: 2
Reputation: 323
Your pickEye
not need to be a listen function, because for onClick={() => props.pickEye(index)}
, () =>
this is already an inline listen function. And pickEye
is your class function. So this will be onClick={() => this.state.pickEye(index)}/>
instead of onClick={() => props.pickEye(index)}/>
So, change :
pickEye = (eye) => {
this.setState({eyeSelecionado: eye});
}
To
pickEye(eye) {
this.setState({eyeSelecionado: eye});
}
And then your button :
<button className={eye.toggled === 'true' ? "button is-white fa fa-eye" : "button is-white fa fa-eye-slash"}
onClick={() => this.state.pickEye(index)}/>
Upvotes: 0