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
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.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With