I'm new to React. Currently I'm creating one app in learning purposes. I'm stuck trying to change color of button on click. When I click on a button, the color of all the buttons are changed. But I need to have just one button active, while others are not active. When I click on different button, the previous active button loses its class and become inactive. Could you help me out?
state = {
clicked: false
};
timeChangeHandler = () => {
this.setState({ clicked: true });
};
render() {
return (
<div>
<button
type="button"
className={
this.state.clicked
? "list-group-item list-group-item-action active"
: "list-group-item list-group-item-action"
}
onClick={this.timeChangeHandler}
>
8:00
</button>
<button
type="button"
className={
this.state.clicked
? "list-group-item list-group-item-action active"
: "list-group-item list-group-item-action"
}
onClick={this.timeChangeHandler}
>
9:00
</button>
</div>
);
}
Your solution would look something like this.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
activeButton: 0
};
}
render() {
const { activeButton } = this.state;
return (
<div>
<button
className={ activeButton === 0 && "active" }
onClick={() => this.setState({activeButton: 0})}
/>
<button
className={ activeButton === 1 && "active" }
onClick={() => this.setState({activeButton: 1})}
/>
<button
className={ activeButton === 2 && "active" }
onClick={() => this.setState({activeButton: 2})}
/>
</div>
);
}
}
Here is a simple example of how you can do it. I map the buttons and use index as the clicked value. But, if you are using your buttons statically as in your code you can use @Kyle's solution.
const buttons = [ { name: "foo" }, { name: "bar" }, { name: "baz" } ]; class App extends React.Component { state = { clicked: null }; handleClick = id => this.setState({ clicked: id }); render() { return ( <div> {buttons.map((button, index) => ( <button className={this.state.clicked === index && "clicked"} onClick={() => this.handleClick(index)} > {button.name} </button> ))} </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
.clicked { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.