Home > Web Front-end > JS Tutorial > How Can a Child Component Update a Parent's State in React Without External Libraries?

How Can a Child Component Update a Parent's State in React Without External Libraries?

Patricia Arquette
Release: 2024-12-03 09:55:11
Original
882 people have browsed it

How Can a Child Component Update a Parent's State in React Without External Libraries?

Parent-Child State Management in React

In a React application, you may encounter scenarios where a child component needs to update the parent's state. While props are immutable by default, there are ways to achieve this functionality without using external libraries like Redux.

Solution Approach

For child-parent communication, you can utilize a callback function passed as props from the parent to the child. Here's an example:

class Parent extends React.Component {
  constructor(props) {
    super(props);

    this.handler = this.handler.bind(this);
  }

  handler() {
    this.setState({ someVar: 'some value' });
  }

  render() {
    return <Child handler={this.handler} />;
  }
}

class Child extends React.Component {
  render() {
    return <Button onClick={this.props.handler} />;
  }
}
Copy after login

In this scenario:

  • Parent passes the handler function as a prop to Child.
  • When the button in Child is clicked, it calls the handler function.
  • The handler function in Parent updates the someVar state within Parent.

Alternative Solution

If you're dealing with unrelated components (e.g., Component 5 and Component 3 in your example), you can restructure your components:

  • Create a new higher-level component that contains the state for both components (Component 1 and Component 3).
  • Pass the state from the higher-level component to the lower-level components as props.

This approach allows you to effectively manage state between unrelated components without relying on intermediate state sharing mechanisms.

The above is the detailed content of How Can a Child Component Update a Parent's State in React Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template