For example, just switching the active classes btw to li. But not with router. I have list like this it is not cicle with map() method. It is static list.
constructor(props) {
super(props);
const parsedUrlQuery = window.location.pathname;
this.state = {
isActive: true
}
}
<ul className='bread list-inline'>
<li className={this.state.isActive ? 'navigation--active' : ''}>All projects</li>
<li> My projects</li>
</ul>
the problem is i don not know how to remove and add class for static list. Could u help me with that.
To delete an item from list with React and JavaScript, we can use some array methods. to create the items state with useState . Then we define the deleteItem function that takes the index of the item to delete and returns a function that calls setItems with (items) => items. filter((_, i) => i !==
You have to change state
somehow. Button click, input change or even from a child component handler of some sort.
In this example, I'm using onClick
in each li
element that triggers such state change:
class App extends React.Component {
constructor() {
super()
this.state = {
activeItem: -1,
items: ['All Projects', 'My Projects'],
}
}
handleItemClick(index) {
this.setState({
activeItem: index,
})
}
render() {
return (
<div>
<ul className='bread list-inline'>
{this.state.items.map((item, index) =>
<li
key={index}
className={this.state.activeItem === index ? 'navigation--active' : ''}
onClick={this.handleItemClick.bind(this, index)}
>
{item}
</li>
)}
</ul>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
ul > li {
cursor: pointer;
}
li.navigation--active {
text-decoration: underline;
}
<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="root"></div>
Let say your li is below
<li className={this.state.isActive ? 'navigation--active' : ''}>All projects</li>
Now change you li to this below LI and add OnClick function "liCkickFun"
<li className='navigation--active' onClick={this.liCkickFun}>All projects</li>
Now in your component add below function
liCkickFun = (event) => {
//check if clicked element has active class then remove it
//and if don't has class then add it
if(event.target.classList.contains('navigation--active')){
event.target.classList.remove('navigation--active');
} else {
event.target.classList.add('navigation--active');
}
}
Hope this will help :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With