Creating a new Todo component

Now that we have a good initial pass at dynamic state affecting our DOM, it's time to create a new component that will allow us to add additional Todo items to our TodoList. We'll call this, well, NewTodo! Create src/NewTodo.js and src/NewTodo.css to start, as per usual. Then, in src/NewTodo.css, give it some default style:

 .NewTodo {
margin: 20px;
padding: 20px;
border: 2px solid #00FFD8;
background: #DDFFEE;
text-align: center;
}

And then, it's time for us to build out our NewTodo component! We start off with our React boilerplate code that we do all the time:

import React, { Component } from 'react';
import './NewTodo.css';

class NewTodo extends Component {
}

export default NewTodo;

Next, we'll build out our constructor() function:

  constructor(props) {
super(props);
this.state = { item: '' };
this.handleUpdate = this.handleUpdate.bind(this);
}

We start off with our call to super(), same as always. Next, we'll set up an initial state with an item property that starts off blank (more on this later). We'll also need to write something to handle updates, so we'll write a bind statement on a handleUpdate() function (which we'll write next):

  handleUpdate(event) {
this.setState({ item: event.target.value });
}

So, when handleUpdate() is called, it is going to take a DOM event, which if we wanted to get the value of the input that is changing, we'd grab it via event.target.value. Finally, let's hit up our render() function:

render() {
return (
<div className="NewTodo">
<input type="text" onChange={this.handleUpdate} />
&nbsp;&nbsp;
<button>Add</button>
</div>
);
}

Most of this code is unremarkable, but note that we have an input here, which is a text type, which reacts to every time the input's value is changed by delegating the handler to the handleUpdate() function we already wrote!

It's time to head back to our TodoList, import the NewTodo component, and add it near the top of our call to render(). At the top of src/TodoList.js, add the following:

import NewTodo from './NewTodo';

And then, add NewTodo into the render() function:

render() {
return (
<div className="TodoList">
<NewTodo />
{this.renderItems()}
</div>
);
}
..................Content has been hidden....................

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