React Tutorials
React ES6
React Hooks
Prior to React 16.8, Class components were the only way to track the status and life cycle of the React component. Performance components were considered "state-less".
With the addition of Hooks, the Work sections are now almost equal to the Class sections. The difference is so small that you will not need to use the Class section on React.
Although Functional sections are selected, there are no current plans to remove Class sections from React.
This section will give you an overview of how to use Classroom components in React.
The parts are independent and can be reused. They work for the same purpose as JavaScript functions, but work independently and restore HTML with render () function.
The components come in two types, Class components and Work components, in this chapter you will learn about Class components.
When you create a React component, the component name must start with a capital letter.
The component must include the extends React.Component
statement, this statement creates the React.Component asset, and gives your component access to React.Component functions.
The component also requires an .render()
method, this method returns HTML.
Create a Class component called Car
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Your React app now has a component called Car, which returns the <h2>
component.
To use this component in your application, use the same syntax as standard HTML: <Car>/
Display the Car
component in the "root" element:
ReactDOM.render(<Car />, document.getElementById('root'));
If there is a constructor()
function on your part, this function will be called when the part is started.
The constructor function is where you start the component features.
In React, component structures must be stored in an object called state
.
You will learn more about the state
later in this lesson.
The job of the constructor is also where you honor the legacy of the parent component by adding a super()
statement, which makes the role of the parent component constructor, and your component has access to all the parent component functions (React.Component
).
Create a constructor function in the Car component, and add a color property:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a Car!</h2>;
}
}
Use the color feature in the render () function:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a {this.state.color} Car!</h2>;
}
}
Another way to manage component structures is to use props
.
Resources are like performance issues, and you post them in the section as attributes.
You will learn more about props
in the next chapter.
Use an attribute to pass a color to the Car component, and use it in the render() function:
class Car extends React.Component {
render() {
return <h2>I am a {this.props.color} Car!</h2>;
}
}
ReactDOM.render(<Car color="red"/>, document.getElementById('root'));
If your component has a constructor function, subsidies should always be forwarded to the builder and React.Component by super()
method.
class Car extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h2>I am a {this.props.model}!</h2>;
}
}
ReactDOM.render(<Car model="Mustang"/>, document.getElementById('root'));
We can refer to internal components:
Use the Car component inside the Garage component:
class Car extends React.Component {
render() {
return <h2>I am a Car!</h2>;
}
}
class Garage extends React.Component {
render() {
return (
<div>
<h1>Who lives in my Garage?</h1>
<Car />
</div>
);
}
}
ReactDOM.render(<Garage />, document.getElementById('root'));
React is about reusing code, and it would be wise to include some of your components in separate files.
To do that, create a new file with an .js
file extension and enter the code inside:
Note that the file should start with the React import (as before), and should end with the automatic export default Car;
.
This is the new file, we named it Car.js
:
import React from 'react';
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
export default Car;
In order to use the Car
component, you must import a file into your application.
Now we import the Car.js
file in the application, and we can use the Car
component as if it was created here.
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';
ReactDOM.render(<Car />, document.getElementById('root'));
React Class components have a built-in state
object.
You may have noticed that we used the state
earlier in the section builder section.
The state
object of the country is where you keep the property values in part.
When the state
item changes, the component renders.
The status item starts with the constructor:
Specify the state
object in the constructor method:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
The state object can contain as many properties as you like:
Specify all the properties your component need:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
state
ObjectLook at the state
object anywhere in the section using the syntax for the word this.state.propertyname
:
Refer to the state
object in the render()
method:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
</div>
);
}
}
state
ObjectTo change the value in the state object, use this.setState()
method.
If the value in the state
object changes, the component will re-supply, which means that the output will change according to new values.
Add a button with an onClick
event that will change the color property:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button
type="button"
onClick={this.changeColor}
>Change color</button>
</div>
);
}
}
Always use the setState()
method to modify the country object, it will ensure that the component knows it has been updated and calls the render () method (and all other life cycle modes).
Each component in React has a life cycle that you can monitor and control during its three main stages.
The three categories are: Mounting, Updating and Unmounting.
Mounting means adding elements to the DOM.
React has four built-in methods that gets called, in this order, when mounting a component:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
The render()
method is required and will always be called, some are selected and will be called when you define them.
The constructor()
method is named before anything else, when the component is started, and is a natural setting for setting the initial state
and other initial values.
The constructor()
method is called props, like arguments, and you should start by driving super(props)
before anything else, this will start the parent builder method and allow the component to gain access to its parent (React.Component
).
The constructor
method is called, by React, every time you make a component:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
The getDerivedStateFromProps()
method is named before assigning element (s) to DOM.
This is a natural place to set the state
object based on the original props
.
It takes the state
as an argument, and returns the object of change to the state
.
The example below starts with a favorite "red" color, but the getDerivedStateFromProps()
method updates the favorite color based on favcol
attribute:
The getDerivedStateFromProps
method is called right before the render method:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
The render()
method is required, and is the method that actually removes HTML from DOM.
A simple component with a simple render()
method:
class Header extends React.Component {
render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
The componentDidMount()
method is named after partial release.
This is where you use the statements that require the component to already be placed in the DOM.
At first my favorite color is red, but give me a second, and it is yellow instead:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
The next phase of the life cycle is where the phase is updated.
The component is updated whenever there is a change in the condition of the state
or props
.
React has five built-in methods that gets called, in this order, when a component is updated:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The render()
method is required and will always be called, some are selected and will be called when you define them.
Also in the updates the getDerivedStateFromProps
method is called. This is the first method called when the part is updated.
This is still a natural place to set a state
object based on original props.
The example below has a button that turns the favorite color to blue, but as the getDerivedStateFromProps()
method, which updates the color with a favcol attribute, the favorite color is still translated as yellow:
If the component gets updated, the getDerivedStateFromProps()
method is called:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
With shouldComponentUpdate()
you can return a Boolean value that specifies whether the React should continue to be given or not.
The default value is true
.
The example below shows what happens when the shouldComponentUpdate()
method returns false:
Stop the component from rendering at any update:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Same example as above, but this time the shouldComponentUpdate()
method returns true
instead:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return true;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
The render()
method is called when the component is updated, it should re-render HTML in DOM, with new changes.
The example below has a button that turns your favorite color to blue:
Click the button to make a change in the component's state:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
In the getSnapshotBeforeUpdate()
method you have access to the props
and state
before the update, which means that even after the update, you can check what the values were before the update.
If the getSnapshotBeforeUpdate()
method exists, you must also enter the componentDidUpdate()
method, otherwise you will get an error.
The example below may seem complicated, but all we do is:
When the part rises it is translated into the favorite "red" color.
When a part is inserted, the timer changes shape, and after one second, the favorite color becomes "yellow".
This action initiates a review phase, and since this section contains the getSnapshotBeforeUpdate()
method, this method is used, and writes the message in the empty DIV1 element.
Then use the componentDidUpdate()
method and write the message to the blank DIV2 object:
Use the getSnapshotBeforeUpdate()
method to find out what the state
object looked like before the update:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.favoritecolor;
}
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
The componentDidUpdate
method is named after the component has been updated in the DOM.
The example below may seem complicated, but all we do is:
When the part rises it is translated into the favorite "red" color.
Once a component is inserted, the timer changes shape, and the color becomes "yellow".
This action initiates a review phase, and since this component has a componentDidUpdate
method, this method is used and writes the message in an empty DIV element:
The componentDidUpdate
method is called after the update has been rendered in the DOM:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
componentDidUpdate() {
document.getElementById("mydiv").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="mydiv"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
The next phase of the life cycle is when a component is removed from the DOM, or downgraded as React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
componentWillUnmount()
The componentWillUnmount
method is named when the component is about to be removed from the DOM.
Click the button to delete the header:
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete Header</button>
</div>
);
}
}
class Child extends React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}
ReactDOM.render(<Container />, document.getElementById('root'));