i'm new on react and try to adding class based on array, but while i click in another button the active class should stay in the last button class when i click the other button, i don't have any clue to do so.
class Child extends React.Component {
render(){
return(
<button
onClick={this.props.onClick}
className={`initClass ${this.props.isClass}`}>
{this.props.text}
</button>
)
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
newClass: null,
};
}
myArray(){
return [
"Button 1",
"Button 2",
"Button 3"
];
}
handleClick (myIndex,e) {
this.setState({
newClass: myIndex,
});
}
render () {
return (
<div>
{this.myArray().map((obj, index) => {
const ifClass = this.state.newClass === index ? 'active' : '';
return <Child
text={obj}
isClass={ifClass}
key={index}
onClick={(e) => this.handleClick(index,e)} />
})}
</div>
)
}
}
ReactDOM.render(<Parent/>, document.querySelector('.content'));
.active {
background: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div class='content'/>