Call parent component method in a child component in React and Typescript

#react #typescript

Last updated on Dec 5, 2020 by Suraj Sharma



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


Parent.tsx

import React from 'react';

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

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


Child.tsx

import React from 'react';

const Child: React.FC = () => {
  return (
    <button>
      Click me
    </button>
  )
};


On click of the button in the <Child /> component you want to call the parent method to change the parent’s label state, defined using useState() hook


To achieve this we have to pass the label setter function as one of the props of the child component.


Parent.tsx

<Child onClick={setLabel}/>


Call the onClick props inside the click event handler in the child component


import React from 'react';

type ChildProps = {
  onClick?:(val: string) => void
};

const Child: React.FC<ChildProps> = ({
  onClick=()=>{}  
}) => {
  const handleClick = () => {
    onClick('Clicked!');
  }
  return (
    <button onClick={handleClick}>
      Click me
    </button>
  )
};


Related Solutions



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