Skip to content Skip to sidebar Skip to footer

Change Button Icon On Click React

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

Solution 1:

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)}));
};

Solution 2:

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)}/>

Post a Comment for "Change Button Icon On Click React"