I am new to react, the question is how to apply any actions to elements (in this case with a list). Here is an example:

let arr = [1, 2, 3, 4]; class List extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { classToggle: '' }; } handleClick() { const newClass = this.state.classToggle === '' ? 'active' : ''; this.setState({ classToggle: newClass }); } render() { return ( <ul> {arr.map(elem => <li className={this.state.classToggle} onClick={this.handleClick}>{elem}</li>)} </ul> ) } } ReactDOM.render(<List />, document.getElementById('app')); 
 .active { color: #FF0000; } 
 <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> 

I know that a class will be added to all list items. The question is how to make the class be added only to the element that was clicked? On js, this is done simply, take jquery:

  $('li').click(function(){ $(this).addClass('active'); }) 

Perhaps I study it incorrectly, since such a simple task caused me difficulties.

    1 answer 1

    For example, you can put <li> into a separate component with its own independent processing of a click:

     let arr = [1, 2, 3, 4]; class List extends React.Component { render() { return ( <ul> {arr.map(elem => <LiElement> {elem} </LiElement>)} </ul> ) } } class LiElement extends React.Component { constructor(props) { super(props); this.state = { classToggle: '' }; } handleClick = () => { const newClass = this.state.classToggle === '' ? 'active' : ''; this.setState({ classToggle: newClass }); }; render() { return ( <li className = {this.state.classToggle} onClick = {this.handleClick} > {this.props.children} </li> ); } } ReactDOM.render( < List / > , document.getElementById('app')); 
     .active { color: #FF0000; } 
     <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> 

    • Thanks for the decision) - Saul Goodman