by changing props

If we pass the state of the parent component as a prop to the child and call setState on the parent, it will cause the re-render of the child component as its props are changed.

Example: This code implements re-render by changing the props passed to the component. 

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    constructor(props) {
        super(props);
 
        // Set initial state of parent
        this.state = { category: "Coder" };
 
        // Binding this keyword
        this.updateState = this.updateState.bind(this);
    }
 
    updateState() {
        // Changing state
        this.setState({ category: "Geek" });
    }
 
    render() {
        return (
            <div>
                <Child category={this.state.category} />
                <button onClick={this.updateState}>
                    Click me!
                </button>
            </div>
        );
    }
}
 
class Child extends Component {
    render() {
        return (
            <div>
                <p>Hi {this.props.category}!</p>
            </div>
        );
    }
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

re-render of child component by changing props

How re-render a component without using setState() method in ReactJS ?

In React, to re-render a class-based component with an updated state we generally use the setState() method. But instead, we can use other methods to re-render a component without using setState().

Similar Reads

Prerequisites:

NPM & Node.js React JS ReactJS props ReactJS forceUpdate() method...

Steps to Create React Application:

Step 1: Create a React application using the following command:...

Method 1: by changing props

If we pass the state of the parent component as a prop to the child and call setState on the parent, it will cause the re-render of the child component as its props are changed....

Method 2: Using the forceUpdate() method

...

Contact Us