javascript - React change state dynamicly for multiple components -
i have issue react component. have this
class sidebaritem extends react.component{ constructor(props) { super(props) this.state = { isactive: false } } handleclick() { var active = !this.state.isactive; this.setstate({ isactive: active }); } render() { var classname = 'item'; if(this.state.isactive){classname = 'active item'} else {classname = 'item'}; return ( <link classname={classname} to={this.props.href} onclick={this.handleclick.bind(this)}> {this.props.label} </link> ); } } export class sidebar extends react.component { constructor(props) { super(props) } render() { var elements = this.props.defaults.elements.map(function (i) { return ( <sidebaritem label={i.label} href={i.href} key={i.label} /> ); }); return ( <div classname={this.props.defaults.class}> {elements} </div> ); } };
my aim change classname active element of menu. can't understand, how must translate elements clear active state , active 1 clicked element?
i think looking this
class menu extends react.component { constructor(){ super() this.state = { items: ['hello', 'world', 'it', 'is', 'me'], active: 0 } } click(index){ this.setstate({active: index}) } render(){ const list = this.state.items.map((item,index) => { return <item key={index} classname={this.state.active === index ? 'active' : ''} text={item} click={this.click.bind(this, index)} /> }) return <ul> {list} </ul> } } class item extends react.component { constructor(){ super(); } render(){ return <li onclick={this.props.click} classname={this.props.classname}> {this.props.text} </li> } } react.render(<menu />, document.getelementbyid('container'));
hope fiddle
Comments
Post a Comment