mardi 24 janvier 2017

React Conditional Rendering with states

I am working in a component where if i click on the NavItem i render an other list of elements

Function changing the state

handleClick() {
  this.setState({
    isActive: !this.state.isActive
  });
};

The Conditional Rendering

if (isActive) {
  SubList = <List hasIcons style="secondary"><ListItem><NavItem href={desktopUrl} title={title}><Icon name={name} />{title}</NavItem></ListItem></List>
}

The List NavItem and the

<ListItem>
    <NavItem href={desktopUrl} title={title} onClick={this.handleClick}>
        <Icon name={name} />
        {title}
    </NavItem>
    {SubList}
</ListItem>

Here the whole component

export default class SportNavItem extends React.Component {

    constructor() {
      super();
      this.state = {isActive: false};
      // This binding is necessary to make `this` work in the callback
      this.handleClick = this.handleClick.bind(this);
    };

    handleClick() {
      this.setState({
        isActive: !this.state.isActive
      });
    };

    render () {

      const { title, desktopUrl, isActive,  name  } = this.props.data;
      // props.childItems; { title, name, isActive, url }

      // const itemId = `nav-${slugEn}`;
      const style = isActive ? 'primary' : 'default';

      let SubList = null;

      if (isActive) {
        SubList = <List hasIcons style="secondary"><ListItem><NavItem href={desktopUrl} title={title}><Icon name={name} />{title}</NavItem></ListItem></List>
      }

      return (
        <List hasIcons style={style}>
            <ListItem>
                <NavItem href={desktopUrl} title={title} onClick={this.handleClick}>
                    <Icon name={name} />
                    {title}
                </NavItem>
                {SubList}
            </ListItem>
        </List>
      );
    }
};

The Component exported

const sampleData = {
  title: 'Football',
  name: 'football',
  isActive: true,
  desktopUrl: '#'
}

ReactDOM.render(
    <div>
        <SportNavItem data = { sampleData }/>
    </div>,
    document.getElementById('app')
);

If i manually change the status isActive to false i can render the SubList. I can not achieve to handle the status onClick and i do not see error in the console. What is possibly wrong? Is there a better way?

Aucun commentaire:

Enregistrer un commentaire