I'm currently working on customizing the styles of some buttons depending on their 'active' status and whether the user is hovering over them. So far, it's partially working but I'm encountering behavior that I can't fully comprehend.
How can I implement conditional styling for a component based on its state and user interaction?
For reference, I have set up an example in this SANDBOX
Here is the primary JS file excerpt:
demo.js
import React from "react";
import PropTypes from "prop-types";
//import { makeStyles } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/styles";
import { Button } from "@material-ui/core";
const useStyles = theme => ({
root: {
backgroundColor: theme.palette.secondary.paper,
width: 500
},
pageButton: {
backgroundColor: "black",
color: "blue",
width: 30,
minWidth: 20,
"&:hover": {
backgroundColor: "green"
}
},
normalButton: {
width: 30,
minWidth: 20,
backgroundColour: "red"
}
});
class Feature extends React.Component {
constructor(props) {
super(props);
this.state = { currentPage: 0 };
}
handleClick(page) {
this.setState({ currentPage: page });
}
fetchPageNumbers() {
return [1, 2, 3];
}
render() {
const classes = this.props.classes;
return (
<div className={classes.root}>
{this.fetchPageNumbers().map((page, index) => {
return (
<div>
<Button
onClick={() => this.handleClick(page)}
key={page}
className={
this.state.currentPage === page
? classes.pageButton
: classes.normalbutton
}
>
{page}
</Button>
<Button
onClick={() => {}}
key={page * 20}
className={classes.normalButton}
>
{page * 20}
</Button>
</div>
);
})}
</div>
);
}
}
Feature.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(useStyles)(Feature);
The issue lies in how the first row of buttons reacts. The second row applies the styles correctly. However, the first row only reflects changes when a button is clicked. What I aim to achieve is setting the state based on whether the current button is active (i.e., state == buttonNumber), and also accounting for user hover interactions across all buttons.