A component passes setState function as a prop to a child component.
B component doesn't pass setState props to a child component so when B component gets fired I get an error saying setState is not a function.
I know if I pass a value I could set it like this value = '' which if there is no value, will be an empty string.
Is there a way to set default value? to the function?
Or how can I execute setState function when only `A component is fired?
const A = () => {
const setState = () => {
console.log("A fire");
};
return <Child setState={setState} />;
};
const B = () => {
return <Child />;
};
const Child = ({ setState }) => {
setState();
return <diva>hello</div>;
};
CodePudding user response:
Is there a way to set default value? to the function?
You could either just add a simple condition if setState exists:
if (setState) {
setState(); // if setState exists - call it
}
or use a shorthand syntax with optional chaining:
setState?.();
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
