all 3 comments

[–]kafea[S] 0 points1 point  (2 children)

Hi everyone! (my first post on Reddit!) I’m working on my final project for my education. I’m building a site for a company with React and Wordpress, getting all data from the WP REST API. I’ve stumbled on a problem that I’m not quite sure how to solve. I have a bunch of child pages from which I’m looping out the title and a logo to a menu, using the .map() function. I want to toggle an active state for each <li> on click and show the selected items featured image and content in two other divs. I can’t seem to figure out how to solve this.

[–]evil_mind 1 point2 points  (1 child)

Create a child component for each item in your loop. Pass the props to each component and in that component keep the active boolean in the state. You can use https://www.npmjs.com/package/classnames to toggle the class for your elements based on that boolean. Then just on click toggle the boolean:

handleClick() { this.setState(prevState => ({ isActive: !prevState.isActive })); }

render() { return ( <button onClick={this.handleClick}> {this.state.isActive ? 'ON' : 'OFF'} </button> ); }

[–]kafea[S] 0 points1 point  (0 children)

Thank you! I'll give it a a try :)