I am facing an issue where the first li element works perfectly when clicked, but for the rest of the elements, I have to click twice to apply the desired styling. Can anyone explain why this behavior is occurring?
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
state={
clicked: false,
index: 0,
arr: ['a','b','c','d','e','f','g','h']
}
handleClick = (i) => {
this.setState({
clicked: !this.state.clicked,
index: i
});
}
render() {
console.log(this.state.index);
return (
<div className='App'>
<ul>
{
this.state.arr.map((el, i) => (
<li key={i} className={(this.state.clicked && this.state.index === i) ? 'clicked':''}
onClick={() => this.handleClick(i)}>{el}</li>
))
}
</ul>
</div>
)
}
}
export default App;
App.css
.App {
text-align: center;
width: 60vw;
margin: 50px auto;
border: 1px solid grey;
}
ul{
list-style: none;
}
li{
padding: 4px 7px;
border: 1px solid grey;
margin-bottom: 15px;
text-align: left;
width: 50%;
cursor: pointer;
}
.clicked{
background: #000;
color: white;
}
The issue lies in applying the clicked class programmatically through CSS. Can someone point out what might be missing in my implementation?