Data & react

May 25, 2022

You'll frequently need to pass data between your react components. If you need to pass data from a parent component to a child component, the easy way is to use props. But what if you want to pass data from a child component to its parent component ?...

Passing data from parent to child component

In our scenario, the child component has for only function to display a count value :

function Child({ childCount }) {

  return (
    <div>
      <p>Count: {childCount}</p>
    </div>
  );
}

The parent component set the child's count by passing it as a prop :

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

  return (
    <div>
      <Child childCount={count} />
      <button onClick={() => setCount((prevCount) => prevCount - 1)}>-</button>
      <button onClick={() => setCount((prevCount) => prevCount + 1)}>+</button>
    </div>
  );
}

Passing data from child to parent component

What if we don't want to deal with the details of the buttons rendering implementation inside the parent component ? And what if at the same time we want to pass data from the child component to the parent component ? In that case you would have to re-write the child component like this :

function Child({ childCount, plusHandler, minusHandler }) {
  const plus = () => {
    plusHandler(new Date());
  };

  const minus = () => {
    minusHandler(new Date());
  };

  return (
    <div>
      <p>Count: {childCount}</p>
      <button onClick={minus}>-</button>
      <button onClick={plus}>+</button>
    </div>
  );
}

We would then have to rewrite the parent component :

function Parent() {
  const [count, setCount] = useState(0);
  const [plusTime, setPlusTime] = useState(new Date());
  const [minusTime, setMinusTime] = useState(new Date());

  const plus = (t) => {
    setCount((prevCount) => prevCount + 1)
    setPlusTime(t)
  };

  const minus = (t) => {
    setCount((prevCount) => prevCount - 1);
    setMinusTime(t)
  };

  return (
    <div>
      <Child childCount={count} plusHandler={plus} minusHandler={minus} />
      <p>Add button clicked at : {plusTime.toString()}</p>
      <p>Minus button clicked at : {minusTime.toString()}</p>
    </div>
  );
}

As you can see you can pass a lot more than value through props, you can also pass functions. Those functions can be used as callbacks to pass information back from a child component to its parent component. Managing state this way has many advantages, in this example the child component doesn't need to keep track of times value nor count values.


Profile picture

Written by Olivier Bonnet who lives and works in Montreal writing a blog that nobody reads 🤪...

© Bonneto 2024