Reputation: 4788
In my React child component I have access to a variable options
which returns an array of objects.
In this component I have a function which checks if there are options:
const hasOptions = () => options.length > 0;
console.log(hasOptions());
This returns true
or false
.
In my parent component I need this boolean value to conditionally add some styling (based on the boolean value).
How do I pass this boolean value from my child to parent component?
Upvotes: 0
Views: 6581
Reputation: 2080
In general you should not do that. React is based on the idea of one directional data flow. Data flows down, from parent to children and events vice versa. So the correct solution would be to lift state to parent component and pass it to the children. But if you absolutely need to do it, you can pass callback to child.
function Parent() {
const [hasOptions, setHasOptions] = useState(false);
return <Child setHasOptions={setHasOptions} />
}
function Child({ setHasOptions }) {
useEffect(() => {
setHasOptions(hasOptions())
}, [options.length, setHasOptions ]);
// ...
}
Upvotes: 2
Reputation: 1075427
If possible, give the parent access to options
and have it provide hasOptions
to the child, rather than doing it the other way around. State should be "lifted up" the component hierarchy (from children to parents) when possible.
If it's not possible, you'll have to have the parent provide a function to the child (as a prop) that it can then use to tell the parent whether it has options. This is more complicated and can lead to unnecessary rendering (for example, the parent rendering the child without the additional styling, the child calling the parent back, and the parent having to re-render with the additional styling).
Upvotes: 0
Reputation: 3844
You can create a state variable in the parent component, and then pass the setXXX
method to the child component, in the child component call the setXXX
method to pass the boolean variable to the parent.
Upvotes: 2