React State
React components (functions) has a built-in state
object.
The state
object is where you store property values that belong to the component.
When the state
object changes, the component re-renders.
Creating the state
Object
The state
object is initialized in the constructor in the following script.
In JavaScript, super
refers to the parent class constructor.
(In this script, it points to the React.Component
implementation.)
Importantly, you can’t use this
in a constructor until after you’ve called the parent constructor.
constructor( props ) {
super( props );
this.state = { brand: "Ford" };
}
|
The
state
object can contain as many properties as you like:
constructor( props ) {
super( props );
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
|
Using the state
Object
Refer to the
state
object in the
render()
method anywhere in the component by using the
this.state.propertyname
syntax.
render( ) {
return (
My { this.state.brand }
It is a { this.state.color } { }
{ this.state.model } { }
from { this.state.year }.
);
}
|
Changing the state
Object
To change a value in the
state
object, use the
this.setState()
method.
When a value in the
state
object changes, the component will re-render, meaning that the output will change according to the new value(s).
JavaScript arrow functions make use of the fat arrow (=>) syntax to define functions.
From the traditional way of declaring functions in JavaScript:
function( ) { ... }
you can move on and use the syntax you can see in the following:
const ( ) => { ... }
The following example adds a button with an
onClick
event that will change the
color
property:
changeColor = ( ) => {
this.setState( { color: "blue" } );
}
render( ) {
return (
My { this.state.brand }
It is a { this.state.color } { }
{ this.state.model } { }
from { this.state.year }.
<button
type = "button"
onClick = { this.changeColor }
> Change color
</button>
);
}
|