How to Pass Data from Child to Parent Component in React (JavaScript and TypeScript Examples)

There are many approaches to passing data from a child component to their parent in React. But in this article, we’ll use a combination of useState and props arguments. If you have many nested children in a tree-like structure which may or may not need this data, you can consider using Context API to create global variables that can be passed around. But for most use cases of sharing data across a couple of components, useState works just fine.

Passing Data from Child to Parent in 4 Steps

Here’s a quick rundown of how it works:

  • Create the data state in the parent, not the child. If you need data in a parent component, move it up from the child component.
// js
const [name, setName] = useState("")
// ts
const [name, setName] = useState<string>("");
  • Next, create a function in the parent to modify that data as needed. In this example, I’ll be creating an event handler that takes in a name value on a button click. This function will not be used in my parent component, but in the child where it is needed.
// js
const handleNameSubmit = (value) => {
    setName(value);
  };
// ts
const handleNameSubmit = (value: string): void => {
    setName(value);
  };
  • Pass that function to the child as a prop.
// js & ts
return (
    <div className="App">
      <div>We're saving a name here!</div>
      <Child handleNameSubmit={handleNameSubmit} />
    </div>
  );
  • Use the function in your child component as needed. Here, I pass in a hardcoded value of 'jen' but you could be passing the value of an input box or something else.
// js
const Child = ({ handleNameSubmit }) => {
  return (
      <button onClick={() => handleNameSubmit("jen")}>
            Submit Name
      </button>
  );
};
export default Child;
// ts
interface Props {
  handleNameSubmit: (name: string) => void;
}

const Child = ({ handleNameSubmit }: Props) => {
  return (
      <button onClick={() => handleNameSubmit("jen")}>
              Submit Name
      </button>
  );
};
export default Child;

Now, when we console log our name state, we're going to see this =>

// in parent component
console.log("The user's name is " + name);

// in console

"The user's name is jen"

Here is the CodeSandBox for the Javascript example, and the CodeSandBox for the TypeScript example.

There you go! You've successfully passed data from the child component to its parent. Let me know if you have any questions.