Leff
Leff

Reputation: 1276

React - toggle visibility of an element not working

I am trying to toggle the visibility of an menu in a React app. I have tried by setting the state property that I change on click. And then I am checking the objects state to toggle visibility. This is the code:

constructor(props) {
    super(props);

    this.state = {
        'menuOpen': false,
    }
}

openMenu() {
    var newState = !this.state.menuOpen;
    this.setState({
        'menuOpen': newState
    });
}

var menuList = React.createClass({
    render: function() {
        return (
          <div className={styles.menuList}>
            <ul>
              <li>Link</li>
              <li>Link</li>
              <li>Link</li>
            </ul>
          </div>
        );
    }
});

render() {
    return (
        <div className={styles.menu}><span className={styles.menuIcon} onClick={this.openMenu.bind(this)} />
            {this.state.menuOpen ? <menuList /> : null}
        </div>
    );
}

I get an error:

> in ./src/components/post/index.js Module build failed: SyntaxError:
> Unexpected token (31:8)
> 
>      }   
>     var menuList = React.createClass({
>             ^

What am I doing wrong?

Upvotes: 1

Views: 653

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104359

Changes:

1. Don't define a class inside another class, if you want a separate class then define outside within same file. We can create multiple classes in same file.

2. Use either es6 or es5 way of creating a react component, you are using es6 way for outer and es5 for inner.

3. Since name starts with small letters are treated as HTML elements, so its a rule that all React components must start with a upper case letter, so instead of menuList use MenuList.

4. var menuList = ..... is not a valid syntax, check more details about class MDN Doc.

Write the code like this:

constructor(props) {
    super(props);

    this.state = {
        'menuOpen': false,
    }
}

openMenu() {
    var newState = !this.state.menuOpen;
    this.setState({
        'menuOpen': newState
    });
}

render() {
    return (
        <div className={styles.menu}><span className={styles.menuIcon} onClick={this.openMenu.bind(this)} />
            {this.state.menuOpen ? <MenuList /> : null}
        </div>
    )
}

class MenuList extends React.Component{
    render() {
        return (
            <div className={styles.menuList}>
                <ul>
                    <li>Link</li>
                    <li>Link</li>
                    <li>Link</li>
                </ul>
            </div>
        );
    }
}

Upvotes: 1

Related Questions