Use Array.map() to Dynamically Render Elements?

Tell us what’s happening:
How does the array I passed turn into the the actual list elements rather than coming out the other side as an array still? Shouldn’t I have to pass each index individually?

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(curr => <li>{curr}</li>);
    console.log(items); // change code here
    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/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/use-array-map-to-dynamically-render-elements

1 Like

Hi there @BLBaylis, great question. When you pass in <ul>{items}</ul>, the array looks like this right?

const items = [
  <li>todo 1</li>,
  <li>todo 2</li>,
  // so on
]

When you pass that array of elements to React, it creates those as DOM nodes for you.

If you want more depth, I suggest reading the documentation and the source code. Otherwise, I’m not exactly sure how the internals work.

1 Like

The map creates an array of DOM elements. When that array is used in the render method, babel/jsx interpreter creates individual DOM elements from each item in your array.

It’s like magic

1 Like

Ah so it is actually React doing it. Don’t know why I found a framework simplifying something so surprising! Would you know if it is tied specifically to render()?

1 Like

So an array in the render method will automatically be iterated through?

1 Like

If it’s an array of DOM elements, then yes, without issue.

2 Likes

Don’t think ofmit as iterating through, but wherever you have a set I feel brackets {} in your render, it will insert the JavaScript. Since items is an array of

  • items they just get dropped in. You can do something similar for tables with Elements , or spans or whatever is needed!
  • 2 Likes

    Great, thanks for clearing that up!

    1 Like

    Ah I see, thanks for your help!