Reputation: 570
I would like to change the class name of my list items based on information passed on keys. But obviously I am doing something wrong.
On every click I like to update the state with key then based on this state I would like to set the class name as active and active CSS should change the style of the list item
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 0
}
this.ChangeColor = this.ChangeColor.bind(this);
}
ChangeColor(key) {
this.setState({
activeIndex: key
})
console.log(this.state.activeIndex)
}
render() {
return (
<div id='header' >
<a href="#default" className="logo">CompanyLogo</a>
<div id='buttons' >
<li key = {0} className={this.state.activeIndex==0 ? 'active' : null } onClick = {this.ChangeColor} >Home</li>
<li key = {1} className={this.state.activeIndex==1 ? 'active' : null } onClick = {this.ChangeColor} >Features</li>
<li key = {2} className={this.state.activeIndex==2 ? 'active' : null } onClick = {this.ChangeColor} >How It Works</li>
</div>
</div>
)
}
}
class App extends React.Component{
constructor(props){
super(props)
}
render() {
return(
<div>
<Header />
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
#header {
overflow: hidden;
background-color: #f4f4f4;
padding: 20px 10px;
}
#buttons{
float:right;
}
#buttons > .active {
background-color: #008CBA; /* Green */
border-radius: 5px;
color: white;
padding: 10px 10px;
text-align: center;
display: inline-block;
font-size: 16px;
margin: 2px
}
#buttons > li {
background-color: white;
border-radius: 5px;
color: #008CBA;
padding: 10px 10px;
text-align: center;
display: inline-block;
font-size: 16px;
margin: 2px
}
#buttons > li:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Upvotes: 1
Views: 1776
Reputation: 1232
The reason that your program doesn't work is that you are not passing any key when you call ChangeColor
. Hence, after the first click your activeIndex
will be undefined. You need to modify these three lines, as shown below, to ensure ChangeColor
knows the key of the item that is clicked. Please notice that you cannot call the function directly like this this.ChangeColor(0)
.
<li key={0} className={this.state.activeIndex == 0 ? 'active' : null} onClick={() => this.ChangeColor(0)} >Home</li>
<li key={1} className={this.state.activeIndex == 1 ? 'active' : null} onClick={() => this.ChangeColor(1)} >Features</li>
<li key={2} className={this.state.activeIndex == 2 ? 'active' : null} onClick={() => this.ChangeColor(2)} >How It Works</li>
Upvotes: 1
Reputation: 54
You need to pass the key/index into the change color function for each item
onClick = {() => this.ChangeColor(0)}
onClick = {() => this.ChangeColor(1)}
etc..
then what you have done should work
Upvotes: 0