Stefan
Stefan

Reputation: 113

ReactJS buttons change color on click

I have 3 buttons in reactjs created with Material UI Buttons.

<>
<Button variant="contained">Button 1</Button>
<Button variant="contained">Button 2</Button>
<Button variant="contained">Button3</Button>
</>

How can I make that when clicking on one, it changes it's color (let's say blue) and the other ones reset to Default?

Upvotes: 0

Views: 260

Answers (1)

TheoWckr
TheoWckr

Reputation: 209

Because React use JSX, you can put javascript in your html component. We can imagine a single state that manage your buttons.

in your component you create a state containing integer

const [buttonSelected, setButtonselected] = useState(0);

I'm using the react hook syntax, but it also depend on you implementation.

buttonSelected is the current value of the state and setButtonselected is the function that change the state. When you call it, React will rerender your component and change the display .

You can now add a click function on your return

...
<Button variant="contained" onClick={() => setButtonSelected(1)}>Button 1</Button>
<Button variant="contained" onClick={() => setButtonSelected(2)} >Button 2</Button>
<Button variant="contained" onClick={() => setButtonSelected(3)}>Button3 </Button>
...

This will change the value of buttonSelected each time you click a button.

We now need to change the color , for that we will use use makeStyle, but there is other way to do so.

First, create a style element outside of your component.

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
            selected: {
                background: 'blue',
            },
            default:{
                background: 'default',
            }
        }
    ),
);

Then call it in your component

const classes = useStyles();

And finally you can set the style that you want depending on the value

...
<Button className={(buttonSelected === 1) ? classes.selected : classes.default} variant.....
<Button className={(buttonSelected === 2) ? classes.selected : classes.default} variant.....
<Button className={(buttonSelected === 3) ? classes.selected : classes.default} variant.....
...

This is a ternary operator, it's the equivalent of

if(buttonSelected === 1){
    return classes.selected
} else {
    return classes.default
}

And it should work. You can learn about it in the conditional rendering of react and in the the styling in react

Dont hesitate if you got any questions :)

Upvotes: 2

Related Questions