To pass data from a child to a parent component in React:

  1. Pass a function as a prop to the Child component.
  2. Call the function in the Child component and pass the data as arguments.
  3. Access the data in the function in the Parent.
import {useState} from 'react';

function Child({handleClick}) {
  return (
    <div>
      <button onClick={event => handleClick(100)}>Click</button>
    </div>
  );
}

export default function Parent() {
  const [count, setCount] = useState(0);

  const handleClick = num => {
    // 👇️ take the parameter passed from the Child component
    setCount(current => current + num);

    console.log('argument from Child: ', num);
  };

  return (
    <div>
      <Child handleClick={handleClick} />

      <h2>Count: {count}</h2>
    </div>
  );
}
 

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *