I'm attempting to create two buttons that will toggle their class when clicked. When button one is clicked, it should add the "active" class to itself and remove the "active" class from the sibling button.
I've made some progress, but I'm encountering an issue where I only want to add the active class when the element is clicked. Initially, the buttons should not have any classes. When the user clicks on the first button, the active class should be added to that button. Subsequently, if the user clicks on the second button, the active class should be removed from the first button and added to the second button. Another issue I'm facing is that when I click on an already selected and active button, the class and state change. It should be such that clicking on an already selected button does nothing, and the button with the active state should stay active. Essentially, it should function similarly to the jQuery toggleClass method.
Here's my updated react code:
import React, { Component } from "react";
import css from "./styles.css";
export default class TypeButtons extends Component {
constructor(props) {
super(props);
this.state = { isActive: false };
}
toggleClass = () => {
this.setState({ isActive: !this.state.isActive })
}
render() {
return (
<div className={css.buttonsContainer}>
<button className={(this.state.isActive ? 'active' : '')} onClick={this.toggleClass}>
Button 1
</button>
<button className={(this.state.isActive ? '' : 'active')} onClick={this.toggleClass}>
Button 2
</button>
</div>
);
}
}
CSS:
.active {
background: green;
}
I've created a CodeSandbox example: https://codesandbox.io/s/vigorous-pare-3zo0s
In summary, the class should only be added when the button is clicked, both buttons should not have the active class by default. Also, clicking on a button with the active class should not change it, the active state should only change when the opposite button is clicked.
Any assistance would be greatly appreciated!