React - Use Array.map() to Dynamically Render Elements

Tell us what’s happening:

I am getting an error telling me that “this.state.toDoList.map” is not a funtion. I’m not sure what I might be doing wrong

Your 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(item => { <li>{item}</li>}); // 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/131.0.0.0 Safari/537.36

Challenge Information:

React - Use Array.map() to Dynamically Render Elements

1 Like

Hi, good work so far! I went through your code and noticed that toDoList is initialized as an empty string, but it needs to be an empty array because the .map() function only works on arrays. Secondly, the map function for the items variable should explicitly return the <li> element and include a key prop (using the index) for each list item. These changes should resolve the errors. Let me know if this works!

2 Likes

That really helped :sweat_smile:. It works now, thank you very much :heart:

1 Like

It’s great to hear that. Happy to help anytime!