Answer the question
In order to leave comments, you need to log in
How to highlight active list item in react?
good afternoon. New to react. I experiment, nothing works. It is necessary to make it as simple as possible so that when you click on an element of the list, it changes its color, and when you select another, it returns the normal one. I did it, but for some reason all the elements are highlighted at once. Can you please give me an example of this code? And can it be done not through className, but through style?
import 'react', {Component} from React;
//css: .active{color:"darkblue"}
export default class App extends Component {
state = {
items : [id:1, content:"asdfasf", id:2, content:"asdfasfd"],
isActive: false
}
render() {
let x = '';
const {items, isActive} = this.state;
return (
<div key={item.id} className={isActive ? x="active'} onClick "какой то код">
{Items.map(items => (
{item.content} );
</div>
);
}}
Answer the question
In order to leave comments, you need to log in
class App extends React.Component {
state = {
items: [
{ id: 69, text: 'hello, world!!' },
{ id: 187, text: 'fuck the world' },
{ id: 666, text: 'fuck everything' },
],
active: null,
}
onClick = e => {
this.setState({
active: +e.target.dataset.index,
});
}
render() {
const { items, active } = this.state;
return (
<div>
{items.map((n, i) => (
<div
key={n.id}
data-index={i}
className={i === active ? 'active' : ''}
onClick={this.onClick}
>{n.text}</div>
))}
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question