Use Array.map() to Dynamically Render Elements - Help Needed with the Mapping Code

What did I do wrong in my map callback in my code below?

I get an error in the console that says there’s an error.

My code so far


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

class MyToDoList extends React.Component {
constructor(props) {
  super(props);
  // change code below this line
  this.state = {
    userInput: "",
    toDoList: []
  }
  // 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 = this.state.toDoList.map(elem => {
    const li = document.createElement("li");
    li.textContent = `${elem}`;
    return li;
  });
  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/84.0.4147.125 Safari/537.36 Edg/84.0.522.61.

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

Link to the challenge:

It worked when I did this:

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

So I got it.

Just need to know why it didn’t work the other way.

Hello there,

This is because of what type of element createElement returns. It returns an object ([object HTMLLIElement]) which cannot be rendered by React in this way.

I suggest you look into working with HTML Elements in React.

Hope this clarifies.