0

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?

meez
  • 3,783
  • 5
  • 37
  • 91
  • Does this answer your question? [How to pass data from child component to its parent in ReactJS?](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs) – Anwer AR Aug 31 '21 at 09:02

3 Answers3

2

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.

The KNVB
  • 3,588
  • 3
  • 29
  • 54
0

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).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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 ]);

  // ...
}