12.1 Child Parent - biswajitsundara/react GitHub Wiki

The child to parent communication is called lifting state up.

  • Lifting state up means moving the state of a component higher up in the component hierarchy
  • So that it can be shared by multiple child components.
  • This can be useful when you have multiple components that need to share the same data,
  • or when you need to update the state of a parent component based on changes in a child component.

To lift state up, we can follow these steps:

  • Identify the state that needs to be shared between components.
  • Move the state to the closest common ancestor of the components that need to access it.
  • Pass the state down to the child components as props.
  • Create callback functions in the parent component to update the state when necessary, and pass these functions down to the child components as props.
  • Update the child components to use the props passed down from the parent component instead of their own state.

Example 1

//Child.jsx
import React, { useState } from "react";

const Child = (props) => {
  const [name, setName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    props.getData(name);
  };

  const handleChange = (e) =>{
    setName(e.target.value);
    console.log(e.target.value)
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={name}
          onChange={handleChange}
        />
        <button>Submit</button>
      </form>
    </>
  );
};

export default Child;
//Parent.js

import Child from "./Child";

const Parent = () => {
  const getData = (data) => {
    console.log(data);
  };
  return <Child getData={getData} />;
};

export default Parent;

Example 2

//Child.jsx

const Child = (props) => {
  return (
    <div>
      <p>Count: {props.count}</p>
      <button onClick={props.increment}>Increment</button>
    </div>
  );
};

export default Child;
//Parent.jsx

import React, { useState } from 'react';
import Child from './Child';

function Parent() {
    const [count, setCount] = useState(0);
  
    // Callback function to update state
    function incrementCount() {
      setCount(count + 1);
    }
  
    return (
      <div>
        <Child count={count} increment={incrementCount} />
      </div>
    );
  }
  
  export default Parent;
⚠️ **GitHub.com Fallback** ⚠️