Why does .map method works differently inside of the render method in React

Tell us what’s happening:
In the second part of the challenge, to modify the “const items =” line, I had to see the solution:

const items = this.state.toDoList.map(i => <li>{i}</li>)

Which is passing the challenge, but whenever I test something similar in my console:

const toDoList = ['eat', 'code', 'sleep']
const items = toDoList.map(item => <li>{item}</li>)

I am getting: Uncaught SyntaxError: Unexpected token '<' ?

  **Your code so far**

const textAreaStyles = {
width: 235,
margin: 5
};

class MyToDoList extends React.Component {
constructor(props) {
  super(props);
  // Change code below this line

  // Change code above this line
  this.handleSubmit = this.handleSubmit.bind(this);
  this.handleChange = this.handleChange.bind(this);
}
handleSubmit() {
  const itemsArray = this.state.userInput.split(',');
  this.setState({
    toDoList: itemsArray
  });
}
handleChange(e) {
  this.setState({
    userInput: e.target.value
  });
}
render() {
  const items = null; // Change this line
  return (
    <div>
      <textarea
        onChange={this.handleChange}
        value={this.state.userInput}
        style={textAreaStyles}
        placeholder='Separate Items With Commas'
      />
      <br />
      <button onClick={this.handleSubmit}>Create List</button>
      <h1>My "To Do" List:</h1>
      <ul>{items}</ul>
    </div>
  );
}
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36

Challenge: Use Array.map() to Dynamically Render Elements

Link to the challenge:

This is a typical error message when a browser cannot interpret JSX

<li>{item}</li>

The above is JSX.
Try running the code below which is pure js.

const toDoList = ['eat', 'code', 'sleep']
const items = toDoList.map(item => item)
items 

It will work

w3schools:

"
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods.

JSX converts HTML tags into react elements.
"

1 Like

Oh thanks, my understandings were messed up I thought inside the render() method before return() statement we write pure JavaScript, then as I posted this question I thought it could be JSX instead. Thanks for confirming!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.