How to update parent state from child in React

#react #typescript

Last updated on May 21, 2021 by Suraj Sharma



In this tutorial, you'll learn how you can pass down data from a child component to its parent component in React.


Suppose you have a function component <Parent /> and a child component <Child /> rendered inside the <Parent />.


Parent.tsx

import React from 'react';

const Parent: React.FC = () => {
  const [label, updateLabel] = React.useState('');

  return (
    <>
      <p>{label}</p>
      <Child />
    </>
  )
}


Child.tsx

import React from 'react';

const Child: React.FC = ({ updateLabel }) => {
  return (
    <input onChange={(event)=>updateLabel(event.target.value)} />
  )
};


When we type something down in the <input /> field in the <Child />, the input field's change event get fired, which is turn calls the updateLabel() method passed down to the <Child /> from the <Parent /> as a props


Pass the setter method from Parent to Child as a props


To achieve this we have to pass the label setter function as one of the props to the <Child />.


Here, I have added a updateLabel property to the component, which accepts the updateLabel() method from the <Parent /> component

Parent.tsx

<Child updateLabel={updateLabel} />


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.