Reputation: 191
I am writing a ReactJS app for menu navigation in which I add a "selected" class on click on div and remove "selected" class from other elements. Now I am stuck in how to remove class from other elements Here is my code
<pre>
**App.js**
class App extends React.Component {
constructor(){
super();
this.state = {
active : "0",
}
}
clickHandler(index){
}
render() {
let menu = this.props.menu; // menu is a array of page name e.g. ['home','about us','contact us']
let style = 0;
return (
{menu.map((menu, index) =>
List clickHandler={this.clickHandler.bind(this, index)} index={index} key={index} menu={menu}
)}
);
}
}
export default App;
** list.js **
import React from 'react';
class List extends React.Component{
constructor(props){
super(props)
this.state = {
focused : "0"
}
}
clickMe(index){
let style = "";
this.setState({focused: index});
if(this.state.focused == index){
console.log(index);
style = "selected";
}
this.props.clickHandler();
}
render(){
let style = "";
if(this.state.focused === this.props.index){
style = "selected";
}else{
style = "";
}
return li className={style} onClick={this.clickMe.bind(this, this.props.index)}>{this.props.menu} /li>
}
}
export default List;
</pre>
Upvotes: 0
Views: 1038
Reputation: 987
My suggestion is create two components
1) List, this component will has inner state number/index of selected/focused item. As props this component will get array of items. In render method you can render parent tag < ol > and < /ol > and in that tag you can rander in foreach cycle list of items, base on index in state and index in foreach cycle you can calculate if item is selected or no. this component will have handler to change selected index this handler you have to pass to item component.
2) second component Item will render < li > tag as pros this component will get item from array and function as callback from parent List component, also flag if item is selected (false/true).
When user click on Item than handler from List component will be called change state in parent than whole list will be re rendered.
Be sure that second component Item has implemented componentWillReceiveProps(nextProps) method. To be able render when selected props changed
Upvotes: 1