Creating and using a helper render() function

Creating and initializing state but not doing anything with it doesn't help us very much, so we'll want to make sure that all of the JSX is built with the help of our state! We'll have to loop over each Todo item that is stored in our state, which we'll name this.state.items, and for each item we'll render the Todo component and, using props, pass in the description of that Todo.

We're going to use the map function here specifically since map will iterate over each item, perform a function, and then store the results as an array. JSX is expecting us to return either a single JSX element or an array of JSX elements, so this will fit our needs quite nicely. We'll also delegate this task to a new function called renderItems() to make sure each of our functions serves a single small purpose:

renderItems() {
return this.state.items.map(description => (
<Todo key={description} description={description} />
));
}

The only new thing here is the addition of the key property. This is an important part of adding multiple items in React via JSX: React has to know how to reference the item in question in some sort of unique way. If React is going to change something, delete it, or otherwise affect the DOM, it has to have something to reference the specific item by.


We're not actually guaranteeing much of anything here with the list of names; if we end up with any duplicates it will cause us issues, but this is just our naive implementation for now.

Return back to the render() function and we'll add a reference to our new renderItems() function instead of the multiple calls to Todo:

render() {
return <div className="TodoList">{this.renderItems()}</div>;
}

Just to be extra sure, let's also add a third item back in our constructor to our initial state. If we can verify this as well, then we know we've implemented everything correctly:

constructor(props) {
super(props);
this.state = { items: ['Item #1', 'Item #2', 'Item #3'] };
}

There we are! Three items, all working appropriately, and all functioning entirely off of the state! That's a pretty good measure of progress!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.174.95