Is it possible to have the style of a button change when clicked? Specifically, I would like the option 1 button to be selected and have its background color changed by default. If I click on the option 2 button, I want only that button to change while leaving option 1 unchanged.
After following the method outlined in this post, I encountered an issue where my buttons were not displaying the desired colors as expected.
Below is a snippet of my code:
import React, {Component} from 'react';
import './OptionButtons.css'
export class OptionButtons extends Component{
constructor() {
super();
this.state = {
selected: "btn1"
};
}
changeColor = (btn) => {
this.setState({ selected: btn });
};
addClass = (btn) => {
if (this.state.selected === btn) return "selected";
else return "notSelect";
};
render() {
return (
<div class = "option">
<h2> Options </h2>
<div class = "buttons">
<button id = "option1Btn" className = {this.addClass("btn1")} onClick = {this.changeColor.bind(this, "btn1")}> Option 1 </button>
<button className = {this.addClass("btn2")} onClick = {this.changeColor.bind(this, "btn2")}> Option 2 </button>
</div>
</div>
);
}
}
Then in OptionButtons.css:
.option {
box-sizing: border-box;
position: relative;
margin-top: 655px;
margin-left: auto;
margin-right: auto;
width: 80%;
max-width: 650px;
}
.option .buttons {
flex: 20%;
display: flex;
justify-content: center;
align-items: center;
}
.option .buttons button {
flex-direction: row;
border-radius: 5px;
padding: 0 1.3rem;
font-family: 'Nunito';
font-style: normal;
font-weight: 700;
font-size: 1.2rem;
line-height: 27px;
text-align: center;
width: 320px;
height: 40px;
left: 50px;
cursor: pointer;
}
#option1Btn{
margin-right: 10px;
}
.selected {
color: "#fff";
background-color: "#00867D";
border: 1px solid "#00867D";
}
.notSelected {
color: "#00867D";
background-color: "#F2F2F2";
border: 1px solid "#F2F2F2";
}
To view the result of my code, click here.