0

I have 2 basic components here and I get an error when trying to map over my elements:

class EleMenu extends Component {
  render(){
    return (
      <li className="eleMenu">{this.props.name}</li>
    )
  }
}

class MainMenu extends Component {
  const rows = []
  this.props.elements.forEach()    //error here
    (e) => {
      rows.push(
        <EleMenu
          name={e.name}
        > 
        <EleMenu/>
      )
    }
  );

  render(){
    return (
      <ul className="mainMenu">
        {rows}
      </ul>
    )
  }
}

It says unexpected token for the line: this.props.elements.forEach()

1 Answer 1

4

Reason is, only methods are allowed inside es classes and you have defined const and running loop also.

This is in proposal stage check this.

Solution:

Either put all the code inside a function and call that function from render method like this:

class MainMenu extends Component {

  renderElement() {
    const rows = []
    this.props.elements.forEach(e => {
      rows.push(
        <EleMenu
          name={e.name}
        > 
        <EleMenu/>
      )}
    )
    return rows;
  }

  render(){
    return (
      <ul className="mainMenu">
        {this.renderElement()}
      </ul>
    )
  }
}

Or put all the code inside render method:

class MainMenu extends Component {

  render(){
    const rows = []
    this.props.elements.forEach(e => {
      rows.push(
        <EleMenu
          name={e.name}
        > 
        <EleMenu/>
      )}
    )

    return (
      <ul className="mainMenu">
        {rows}
      </ul>
    )
  }
}

Suggestion:

Better to use array.map, instead of using forEach and then pushing the elements inside an array.

Like this:

class MainMenu extends Component {
  render() {
    return (
      <ul className="mainMenu">
        {
          this.props.elements.map(e => (
            <EleMenu
              key={e.name}
              name={e.name}
            /> 
          ))
        }
      </ul>
    )
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I assume he is still not going to display li items as he wants since no .map() on rows isn't he?
Component is returning rows which will be rendered in return statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.