Migrating the AddTodo component

Next, we are going to migrate the AddTodo component. Here, we are going to use a State Hook to handle the input field state.

Let's migrate the AddTodo component now:

  1. Edit src/AddTodo.js and adjust the import statement to import the useState Hook from React:
import React, { useState } from 'react'
  1. Remove the class component code. We are going to define a function component instead now.
  2. First, we define the function, which accepts only one prop—the addTodo function:
export default function AddTodo ({ addTodo }) {
  1. Next, we define a State Hook for the input field state:
    const [ input, setInput ] = useState('')
  1. Now we can define the handler functions for the input field and the add button:
    function handleInput (e) {
setInput(e.target.value)
}

function handleAdd () {
if (input) {
addTodo(input)
setInput('')
}
}
  1. Finally, we return and render the input field and the add button:
    return (
<form onSubmit={e => { e.preventDefault(); handleAdd() }}>
<input
type="text"
placeholder="enter new task..."
style={{ width: 350, height: 15 }}
value={input}
onChange={handleInput}
/>
<input
type="submit"
style={{ float: 'right', marginTop: 2 }}
disabled={!input}
value="add"
/>
</form>
)
}

As we can see, using the State Hook makes state management much simpler. We can define a separate value and setter function for each state value, instead of having to deal with a state object. Furthermore, we do not need to destructure from this.state all the time. As a result, our code is much more clean and concise.

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

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