Making the AddTodo component dynamic

After making our App component dynamic, it is time to make all of our other components dynamic as well. We are going to start from the top, with the AddTodo component.

Let's make the AddTodo component dynamic now:

  1. In src/AddTodo.js, we first define a constructor, which sets the initial state for the input field:
export default class AddTodo extends React.Component {
constructor (props) {
super(props)

this.state = {
input: ''
}
}
  1. Then, we define a method for handling changes in the input field:
    handleInput (e) {
this.setState({ input: e.target.value })
}
  1. Now, we are going to define a method that can handle a new todo item being added:
    handleAdd () {
const { input } = this.state
const { addTodo } = this.props

if (input) {
addTodo(input)
this.setState({ input: '' })
}
}
  1. Next, we can assign the state value and handler methods to the input field and button:
    render () {
const { input } = this.state

return (
<form onSubmit={e => { e.preventDefault(); this.handleAdd() }}>
<input
type="text"
placeholder="enter new task..."
style={{ width: 350, height: 15 }}
value={input}
onChange={this.handleInput}
/>
<input
type="submit"
style={{ float: 'right', marginTop: 2 }}
disabled={!input}
value="add"
/>
</form>
)
}
  1. Finally, we need to adjust the constructor in order to re-bind the this context for all of the handler methods:
    constructor () {
super(props)

this.state = {
input: ''
}

this.handleInput = this.handleInput.bind(this)
this.handleAdd = this.handleAdd.bind(this)
}

Now, our AddTodo component will show a disabled button as long as no text is entered. When activated, clicking the button will trigger the handleAdd function that has been passed down from the App component.

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

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