The spread operator

Remember a little bit earlier in the chapter, when we wrote an ellipse and then a variable name? Any time you do that, you're telling JavaScript to stuff the rest of the unmatched stuff into here and join it to the current data structure:

    const [item1, item2, ...rest] = [
"Write some code",
"Change the world",
"Take a nap",
"Eat a cookie"
];

This line of code tells JavaScript that the item in the first spot goes into the item1 variable, the item in the second spot goes into the item2 variable, and then everything else after that goes into the rest variable. We can take advantage of this as well when we want to add items onto an array in a non-destructive way. Remember the addTodo() function that lives in src/TodoList.js? Let's take a look at that in greater detail to see how we can use array spreads elsewhere:

  addTodo(item) {
this.setState({ items: [...this.state.items, item] });
}

This line of code is telling JavaScript to set the items key in the component's state to be equal to the current value of this.state.items, and then concatenate item onto the end of that list. The code is identical to this:

this.setState({ items: this.state.items.concat(item) });

You can also do this with objects in JavaScript code with Babel's most recent update in Create React App, which is great for state modification, since state modification is just changing objects around! Let's head back to src/App.js and write a sample bit of code that also sets a background color for our header. We'll start off with our object spread and set a new variable called moreDetails:

const moreDetails = {
...details,
header: "Best Todoifier",
background: "black"
};

We're just taking the details data structure, and then on top of that, we're either adding new keys or replacing values for existing keys. Next, we'll need to modify the headerDisplay function to be able to work with a background color being passed in:

const headerDisplay = ({
header: title = "Todo List",
headerColor: color = "blue",
background: background = "none"
}) => <h2 style={{ color: color, background: background }}>{title}</h2>;

The final step of this is to change the call in the App component to pass in moreDetails to the header instead of details or a blank object:

const App = () => (
<div className="App">
{headerDisplay(moreDetails)}
<br />
<TodoList />
</div>
);

After you save and reload, you should see the following:

The line of code for the Object spread is the equivalent of us writing the following:

const moreDetails = Object.assign({}, details, {
header: "Best Todoifier",
background: "black"
});

It's just a little more concise and easier to read, so it's great that the Create React App team and the Babel team made this supported in the most recent version!

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

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