Bringing state into our component

Part of declaring state to a class component is to start off with an initial or default state. We can't do that without telling JavaScript what to do when our class is actually instantiated, so our class will need to have a constructor to handle that work. In our Todo class, we'll build out our constructor function, which will take in props as its single argument:

  constructor(props) {
super(props);
this.state = {
description: props.description,
done: false
};
}

JavaScript knows to use constructor() as our constructor since that is a language construct, and we know it needs to take in props. Since we're extending off of React's Component class, we need to call super() as our first line of code in constructor(). This tells JavaScript to instead use the code in constructor() of Component to set up whatever it needs to. Next, we set the state by declaring a new variable attached to our class called, uninterestingly enough, this.state. We make it a plain object with a key of description, which just stores the passed-in description on the props argument. It also has a property called done that starts off with a default value of false (since we should not create our tasks as already done). This code by itself won't actually do anything, so let's also change our render() function to take advantage of our state:

  render() {
return <div className="Todo">{this.state.description}</div>;
}

Nothing has quite changed yet. Instead, we'll need to add some form of interactivity to make the case for using state really known!

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

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