thx for any help.
How can I pass down setState to a child component and use the c argument without a typescript error?
Parent: Passing down setState
export interface State {
value1: string;
value2: string;
}
const Parent = () => {
const [state, setState] = useState<State>({
value1: "test",
value2: "test",
});
return (
<React.Fragment>
<Child setState={setState} />
</React.Fragment>
);
};
export default Parent;
Child: use setState with c as argument, c is read underlined with a type error
type Props = {
setState: Dispatch<State>;
};
const Child: React.FC<Props> = ({ setState }) => {
return (
<React.Fragment>
<button
onClick={() => {
//c is read underlined: Argument of type '(c: any) => any' is not assignable
//to parameter of type 'State'.
//Type '(c: any) => any' is missing the following properties from type
//'State': value1, value2
setState((c) => {
return {
...c,
value2: "HelloWorld",
};
});
}}
/>
</React.Fragment>
);
};
export default Child;
try this, or replace <any>
with your state type.
type Props = {
setState: React.Dispatch<React.SetStateAction<any>>;
};
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