Home > OS >  how can i pass a useState hook defined with typescript down to another react component?
how can i pass a useState hook defined with typescript down to another react component?

Time:10-16

I am having some difficulties passing down a useState hook down from one component to another component using Typescript

Here is a very simple code that has only two files to show this problem:

the App component which is the entry point of the example

import { useState } from 'react';
import './App.css';
import Header from './Components/Header';

type personType = {
 name: String,
 language: String
}

const initialPerson ={
 name : 'james',
 language: 'english'
} 

function App() {
 const [ person, setPerson] = useState<personType>(initialPerson);

 return (
   <div className="App">
     <Header setPerson={setPerson} person={person}/>
   </div>
 );
}

export default App;

the Header component that receives the useState as props



import { personType } from "../../App"

const Header = ({person, setPerson}:{person: personType, setPerson:any}) => {

  const handleTranslate = () => {
    setPerson({name:'john', language:'french'})
  }
  return(
    <div>
      <h1>TYPESCRIPT TEST</h1>
      <button onClick={handleTranslate}>clickMe</button>
      {person.name}
      {person.language}
    </div>
  )
}

export default Header

Now i am having trouble redefining the useState function 'setPerson' i am leaving it to :any for now because i can't seem to be able to find the right syntax in the there for the function argument.

i have tried :

 setPerson:(personType)=> personType

the return type is fine, it is the argument that i cannot find the syntax for...

CodePudding user response:

First export your type personType so that it can be accessible in other components. Either export it from same component or export it from another typescript file just like below.

export type personType = {
  name: String;
  language: String;
}; 

Then you have to import this type in Header Component

import React, {  useState, FC } from "react";
import { personType } from "../App";
type IHeaderProps = {
  person: personType;
  setPerson: (person: personType) => void;
};
const Header: FC<IHeaderProps> = ({ person, setPerson }) => {
  const handleTranslate = () => {
    setPerson({ name: "john", language: "french" });
  };
  return (
    <div>
      <h1>TYPESCRIPT TEST</h1>
      <button onClick={handleTranslate}>clickMe</button>
      {person.name}
      {person.language}
    </div>
  );
};

You need to just define what props type the Header component will receive. In our case one is person of type personType and second is function I just test it and it is working perfect. I hope this will answer your question. If it does, then please check the icon to mark it as accepted answer.

Thanks !

  • Related