Defining the class component

We first write our app as a traditional class component, as follows:

  1. First, we remove all code from the src/App.js file.
  2. Next, in src/App.js, we import React:
import React from 'react'     
  1. We then start defining our own class component—MyName:
class MyName extends React.Component {
  1. Next, we have to define a constructor method, where we set the initial state object, which will be an empty string. Here, we also need to make sure to call super(props), in order to let the React.Component constructor know about the props object:
    constructor (props) {
super(props)
this.state = { name: '' }
}
  1. Now, we define a method to set the name variable, by using this.setState. As we will be using this method to handle input from a text field, we need to use evt.target.value to get the value from the input field:
   handleChange (evt) {
this.setState({ name: evt.target.value })
}
  1. Then, we define the render method, where we are going to display an input field and the name:
   render () {
  1. To get the name variable from the this.state object, we are going to use destructuring:
       const { name } = this.state

The previous statement is the equivalent of doing the following:

       const name = this.state.name
  1. Then, we display the currently entered name state variable:
    return (
<div>
<h1>My name is: {name}</h1>
  1. We display an input field, passing the handler method to it:
                <input type="text" value={name} onChange={this.handleChange} />
</div>
)
}
}
  1. Finally, we export our class component:
export default MyName

If we were to run this code now, we would get the following error when entering text, because passing the handler method to onChange changes the this context:

Uncaught TypeError: Cannot read property 'setState' of undefined
  1. So, now we need to adjust the constructor method and rebind the this context of our handler method to the class:
    constructor (props) {
super(props)
this.state = { name: '' }
this.handleChange = this.handleChange.bind(this)
}
There is the possibility of using arrow functions as class methods, to avoid having to re-bind the this context. However, to use this feature we need to install the Babel compiler plugin, @babel/plugin-proposal-class-properties, as it is not a released JavaScript feature yet.

Finally, our component works! As you can see, there is a lot of code required to get state handling to work properly with class components. We also had to rebind the this context, because otherwise our handler method would not work. This is not very intuitive, and is easy to miss while developing, resulting in an annoying developer experience.

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

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