The React.Component base class allows us to tap into what we call the Component Lifecycle. Its methods give us control into how our components work, and if we’d like to use them, we have to build out a class component that extends the React.Component parent class:
class FooComponent extends React.Component {}
One integral part of creating components as classes is that you have the ability to set up a data object that your component might need to be concerned with by way using state as we call it and setting that object up on our constructor method. Once we have some data that we can render out to the DOM we need a vehicle that will allow us to render that data - this is achieved by returning some sort of JSX from within the life-cycle hook called render.
class FooComponent extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return <div>Hello, I am Foo Component</div>;
}
Our final component should look like this.
class FooComponent extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return <div>Hello, I am Foo Component</div>;
}
}
this.state = {
message: "Hello from App State!!"
};
div to reference the state object. Remember the this keyword when pointing to an object on the Class constructor.render() {
return <div>{this.state.message}</div>;
}
Lets take the functionality of this class component that we built earlier and extend it just a little bit. Declare a Functional Component called RenderMessage inside this CodeSandbox.
div who’s child is props.messageApp class pass in that RenderMessage component and pass down a message prop to RenderMessage. This message prop should be set equals to the message property on the state object.