1

I am rendering the unordered list elements based on array of objects. Here is my list array return inside this.state.

this.state = {
      cards: [{name: "card1", id: 1}, {name: "card2", id: 2}, {name: "card3", id: 3}]
    };

Using render() i will be listing the list elements.

render() {
    return ( <ul>
        this.state.cards.map((card) => { 
          return <li>{card.name}</li> 
        });
      </ul>
    )
  }

Uncaught Error: Module build failed: SyntaxError: Cards.js: Unexpected token (26:41). So the error is exactly at this point.enter image description here

1
  • Interestingly your error snapshot shows that you are using -> sign for an arrow function while the code snippet is using correct => sign Commented Sep 30, 2017 at 9:19

2 Answers 2

3

You just need to wrap your js code in curly braces

render() {
  return (
    <ul>
      {this.state.cards.map((card) => { 
        return <li>{card.name}</li>
      })}
    </ul>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

Put curly braces when you want to use the value of a variable inside HTML.

The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string.

In your case like this:

render() {
    return ( 
      <ul>
        {this.state.cards.map(card => <li>{card.name}</li>)}
      </ul>
    );
}

My approach:

render = () => {
   const { cards } = this.state; // Destructuring assignment  
   const cardsDraw = cards.map(x => <li key={x.id}>{x.name}</li>);
 return (
   <ul>
     {cardsDraw}
   </ul>
  );
};

Comments

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.