loading

React Class


Components work similarly to functions, returning HTML elements.


React Components

Components are code segments that are both self-contained and reusable. They fulfill the same purpose as JavaScript functions, but they operate in isolation and produce HTML.

 

Components are divided into two types: class components and function components. In this course, we will focus on function components.

 

Class components are commonly utilized in earlier React code bases. It is now recommended to use Function components alongside Hooks, which were introduced in React 16.8. There is an optional section on Class Components for your reference.

Create Your First Component

When establishing a React component, its name must begin with an uppercase letter.

Class Component

A class component must have the extends React.Component line. This statement creates an inheritance from React.Component and grants your component access to its functionalities.

The component also requires the render() method, which returns HTML.

Example

Create a Class component called Car

				
					class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}
				
			

Function Component

Here’s the same example as earlier, but with a Function component instead.

A Function component returns HTML and acts similarly to a Class component; however, Function components may be constructed with considerably less code, are easier to grasp, and will be used in this tutorial.

Example

Create a Function component called Car

				
					function Car() {
  return <h2>Hi, I am a Car!</h2>;
}
				
			

Rendering a Component

Your React application now has a component called Car, which returns a <h2> element.

To utilize this component in your application, use similar syntax to conventional HTML. <Car />

Example

Display the Car component in the “root” element:

				
					const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
				
			

Props

Props are another way to handle component props.

Props are similar to function arguments, and you pass them into the component as attributes.

Props will be covered in further detail in the following chapter.

Example

Pass a color to the Car component via an attribute and utilize it in the render() function.

				
					class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.color} Car!</h2>;
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car color="red"/>);
				
			

Props in the Constructor

If your component contains a constructor function, the props should always be provided to both the constructor and the React.Component using the super() method.

Example

				
					class Car extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>I am a {this.props.model}!</h2>;
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car model="Mustang"/>);
				
			

Components in Components

We can refer to components within other components:

Example

Use the Car component within 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>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
				
			

Components in Files

React is all about reusing code, thus it can be beneficial to keep some of your components in distinct files.

To achieve this, create a new file with a .js extension and place the code within it:

Note that the file must begin by importing React (like before) and end with the sentence export default Car;.

Example

This is the new file, which we named Car.js :

				
					import React from 'react';

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

export default Car;
				
			

To utilize the Car component, import the file into your application.

Example

Now that we have imported the Car.js file into the application, we can utilize the Car component as if it had been created here.

				
					import React from 'react';
import ReactDOM from 'react-dom/client';
import Car from './Car.js';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
				
			

React Class Component State

React Class components include a built-in state object.

You may have noted that we mentioned state earlier in the component constructor section.

The state object stores the component’s property values.

When the state object changes, the component redraws.

Creating the state Object

The state object is initialized in the constructor.

Example

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 have as many characteristics as you want.

Example

Specify all the attributes your component requires.

				
					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>
    );
  }
}
				
			

Using the state Object

Using the this.state.propertyname syntax, you may access the state object anywhere in the component.

Example

Please 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>
    );
  }
}
				
			

Changing the state Object

To update a value in the state object, call the this.setState() method.

When a value in the state object changes, the component re-renders, which means that the output will change to reflect the new value(s).

Example

Add a button with a onClick event to modify the color attribute.

When changing the state object, always use the setState() function; this ensures that the component is aware of the changes and performs the render() method (as well as all other lifecycle methods).

------ example mukavu ------

Lifecycle of Components

Each component in React has a lifecycle that you can track and manage throughout three distinct phases.

There are three phases:Mounting, Updating, and Unmounting.

Mounting

Mounting means inserting elements into the DOM.

When mounting a component, React calls these four built-in functions in the following order:

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

The render() method is necessary and will always be called; the others are optional and will only be called if you specify them.

constructor

When the component is started, the constructor() method is invoked first, and it is the obvious place to configure the initial state and other initial settings.

The constructor() method is invoked with the props as arguments, and you should always begin by calling super(props), which will commence the parent’s constructor method and allow the component to inherit methods from its parent (React.Component).

Example

React calls the constructor method every time you create 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>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
				
			

getDerivedStateFromProps

The getDerivedStateFromProps() method is invoked just before rendering the element(s) in the DOM.

This is the logical location to set the state object based on the starting properties.

It accepts state as an argument and returns an object containing modifications to the state.

The example below begins with the favorite color being “red”, however the getDerivedStateFromProps() method modifies the preferred color based on the favcol attribute:

Example

The getDerivedStateFromProps method is invoked just 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>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header favcol="yellow"/>);
				
			

render

The render() method is of course invoked when a component is modified; it must re-render the HTML to the DOM with the new changes.

The example below includes a button that changes the favorite color to blue:

Example

Click the button to modify the component’s state:

				
					class Header extends React.Component {
  render() {
    return (
      <h1>This is the content of the Header component</h1>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
				
			

componentDidMount

After the component is rendered, the componentDidMount() function is called.

Statements requiring the component to already be in the DOM can be executed here.

Example

My favorite color is first red, but after a moment it becomes yellow:

				
					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>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
				
			

Updating

The updating of a component is the next stage of its lifecycle.

Every time a component’s state or props change, the component is updated.

Five built-in React methods are called when a component is modified, in this order:

  1. getStateDerivedFromProperties()
  2. shouldComponentUpdate ()
  3. render()
  4. acquireSnapshotPriorToUpdate()
  5. componentDidUpdate()

While the other methods are optional and will only be invoked if they are defined, the render() method is necessary and will always be called.

getDerivedStateFromProps

The getDerivedStateFromProps() method is invoked just before rendering the element(s) in the DOM.

This is the logical location to set the state object based on the starting properties.

It accepts state as an argument and returns an object containing modifications to the state.

The example below begins with the favorite color being “red”, however the getDerivedStateFromProps() method modifies the preferred color based on the favcol attribute:

Example

The getDerivedStateFromProps() method is invoked just before the render method.

----- exmaple mukavu -----

shouldComponentUpdate

You can return a Boolean value indicating whether or not React should carry on rendering using the shouldComponentUpdate() method.

True is the default value.

What occurs when the shouldComponentUpdate() method returns false is illustrated in the following example:

Example

At any update, stop the component from rendering:

----- exmaple mukavu -----

Example

The identical case as before, except this time the shouldComponentUpdate() function yields a true result:

----- exmaple mukavu -----

render

The render() method is of course invoked when a component is modified; it must re-render the HTML to the DOM with the new changes.

The example below includes a button that changes the favorite color to blue:

Example

Click the button to modify the component’s state:

----- exmaple mukavu -----

getSnapshotBeforeUpdate

The getSnapshotBeforeUpdate() method provides access to the props and state before to the update, allowing you to inspect the values before the change even after it has occurred.

If the getSnapshotBeforeUpdate() function is present, you must also add the componentDidUpdate() method; otherwise, you will receive an error.

The example below may appear difficult, yet all it does is this.

When the component is mounted, it is shown in the favorite color “red”.

When the component is installed, a timer changes the state, and after one second, the favorite color is “yellow”.

This action initiates the update phase, and because this component includes a getSnapshotBeforeUpdate() method, it is invoked, writing a message to the empty DIV1 element.

The componentDidUpdate() method is then run, and a message is written to the empty DIV2 element:

Example

To see how the state object appeared before to the change, use the getSnapshotBeforeUpdate() method:

----- exmaple mukavu -----

componentDidUpdate

The componentDidUpdate function is called after the component has been updated in the DOM.

The example below may appear difficult, yet all it does is this.

When the component is mounted, it is shown in the favorite color “red”.

When the component is installed, a timer changes the status, and the color turns “yellow”.

This action initiates the update phase, and because this component contains a componentDidUpdate function, this method is run, which writes a message in the empty DIV element.

Example

The componentDidUpdate function is called once 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>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
				
			

Unmounting

The next part of the lifecycle occurs when a component is removed from the DOM, also known as unmounting in React.

React has only one built-in method that is called when a component is unmounted.

  • componentWillUnmount()

componentWillUnmount

The componentWillUnmount function is invoked when a component is about to be removed from the DOM.

Example

Click the button to remove the header:

----- exmaple mukavu -----

Share this Doc

React Class

Or copy link

Explore Topic