Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue with passing hook to child typescript

Tags:

I have a react component using hooks. My parent component looks like this:

const Parent = () => {     const [isActive, setIsActive] = useState(false);     return (      <Child isActive={isActive} setIsActive={setIsActive} />    ); } 

and here is the child component

type Props = {    isActive: boolean;    setIsActive: () => void; } const Child = ({ isActive, setIsActive}: Props) {    // component }  

the error I am seeing is

Type error: Type 'Dispatch < SetStateAction>' is not assignable to > type '() => void'. TS2322

like image 536
peter flanagan Avatar asked Feb 07 '19 14:02

peter flanagan


People also ask

How do you pass a function from parent to child in TypeScript?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.

How do you pass data from parent to child in React hooks?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

Can we use hooks in TypeScript?

You should definitely use hooks if you want some TypeScript. There are numerous reasons why you could avoid TypeScript, using React or not. But if you do choose to use it, you should definitely use hooks, too.

How do you pass props in React hooks?

In order to pass the isActive prop from the parent (MyCard) to the child (MyButton), we need to add MyButton as a child of MyCard. So let's import MyButton at the top of the file. import MyButton from "./Button"; Then, let's add MyButton as a child in the return statement of MyCard component.


1 Answers

Your Props type for Child is incorrect. React types the setIsActive as Dispatch, which is defined as:

type Dispatch<A> = (value: A) => void; 

You're missing the value argument from your type. This should be correct (also note that it needs to be a colon not an equal sign):

type Props = {    isActive: boolean;    setIsActive: (active: boolean) => void; } const Child = ({ isActive, setIsActive}: Props) {    // rest of the component }  
like image 141
Jacob Gillespie Avatar answered Oct 17 '22 20:10

Jacob Gillespie