I'm using Material UI with TypeScript in React. When a user clicks the button, I want the button to be highlighted. Currently, this code will change the buttons color, but when I click another button, that also gets highlighted. I'm trying to only have one button highlighted at a time so when I click a different button, I want the previous button to be set to the regular class and the new button to be set to the clicked class. If I click the button again, it will remove the class, but I only want the "clicked" class to only be the current button. I've seen this done with indexes, but am wondering what the best way to approach this would be. Any help is appreciated.
I'm currently styling the clicked class in index.css to override material-ui themes:
index.css
.btnClass.clicked {
background-color: #1976D2;
color: #FFFFFF;
}
// ...
<TableBody>
{state.currentUsers
.slice(
page * rowsPerPage,
page * rowsPerPage + rowsPerPage
)
.map((users) => {
return (
<SelectUser
key={Number(user.uid)}
name={user.name}
/>
);
})}
</TableBody>
import React, { useState } from "react";
import Button from "@material-ui/core/Button";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import { useStyles } from "./useStyles";
export function SelectUser(props) {
const classes = useStyles();
const [btnClass, setBtnClass] = useState(false);
return (
<TableRow className={classes.tableRow} key={props.uid}>
<TableCell component="th" scope="row" align="left">
// when button is clicked, set current button to clicked class and all other buttons to unclicked
<Button
className={btnClass ? "btnClass clicked" : "btnClass"}
onClick={() => {
props.setUser(props.user);
btnClass ? setBtnClass(false) : setBtnClass(true); // set previous button to unclicked
}}
>
{ props.id}
</Button>
</TableCell>
<TableCell component="th" scope="row" align="right">
{props.name}
</TableCell>
</TableRow>
);
}