Reputation: 73
How to set props type of "a React useState function"
// ParentComponent.tsx
import { useState } from "react"
import ChildComponent "./ChildComponent"
const ParentComponent = () => {
const [prompt, setPrompt] = useState<boolean>(false)
return <ChildComponent setPrompt={setPrompt}/>
}
// ChildComponent.tsx
interface ChildComponentProps {
setPrompt: Function // ✅ WORKED but inaccurate!
setPrompt: (value: boolean) => void // kinda WORKED thanks @acemarke!
setPrompt: typeof React.useState // 🚫 DOESNT WORK!!!
}
const ChildComponent = (props: ChildComponentProps) => {
return <button onClick={() => props.setPrompt(false)}>Button</button>
}
Upvotes: 0
Views: 569
Reputation: 187004
If you hover over setPrompt
in your code editor you should see the type:
Dispatch<SetStateAction<boolean>>
Those types come from inside React. So you either want to import them:
import type { Dispatch, SetStateAction } from 'react'
Dispatch<SetStateAction<boolean>>
Or just use them from the React
namespace.
React.Dispatch<React.SetStateAction<boolean>>
WHich makes ChildComponentProps
something like:
interface ChildComponentProps {
setPrompt: React.Dispatch<React.SetStateAction<boolean>>
}
Playground with no type errors
Upvotes: 3