Thought leadership from the most innovative tech companies, all in one place.

How to Pass Props from Child to Parent Component in React

Learn this neat little trick to pass chunks of props back up the component tree!

image

Quick and easy

If you've used React, you have obviously passed data down from a parent component to a child using props.** This is called uni-directional data flow**.

What if I showed you a little trick which could allow you to conversely pass small chunks of props from the CHILD component back up to the PARENT component?

Here's the trick — very simple. We have 2 components:

  • Parent: App.js

  • Child: Child.js

Use the following steps:

  • Create a function inside your parent component, pass it a parameter and log that parameter using console.log .

  • Pass the function name as props into your child component render.

  • Invoke the function from props inside your child component.

  • Pass in your data as an argument inside the invocation.

  • Viola.

Parent component:

import Child from "./Child";

function App() {
  const pull_data = (data) => {
    console.log(data); // LOGS DATA FROM CHILD (My name is Dean Winchester... &)
  };

  return (
    <div className="App">
      <Child func={pull_data} />
    </div>
  );
}

export default App;

Child component:

const Child = (props) => {
  props.func("My name is Dean Winchester & this is my brother Sammie");

  return (
    <>
      <h1>I am the Child Component!</h1>
    </>
  );
};

export default Child;

It's that simple!

Also, notice that inside Child.js , the use of React Fragments <> ... </> .

This allows us to create fewer DOM nodes, giving our app a small performance boost. It also helps with debugging (less clutter of div s).

Thanks for reading — I hope this provided some good value.

Visit me at PJCodes.com.

Further Reading

Composable Link Component that Works in Any React Meta-Framework




Continue Learning