Is there a way in ReactJS for a component to find out who it's parent is?
I haven't found a React way to do this - from what I can see, the idea is to pass callbacks down to the child from the parent, and the child calls the callback - unaware of the fact that the callback is actually on the parent.
I've tried setting an "owner" property, and that idea seems to work, but I wonder what's the best approach?
e.g.
<Parent>
<Child owner={this}/>
</Parent>
Then in the child component, I can do owner.method
, and it seems to work fine. I know this isn't a true parent/child relationship, but is the closest I've found in my tests.
Some may say that callbacks are a cleaner way of doing this, but the parent/child relationship for some things (e.g. RadioButtonGroup and RadioButton) seems natural and would benefit from knowing this relationship, in my opinion.
The thing that I don't like about the idea that it's not supported is that HTML can be marked up with zero javascript - and it has implied, default functionality - some elements are required to have parents - they are defined as children of other elements (e.g. ul and li). This can't happen in JSX because if there is interaction between the elements - there has to be javascript events that bind the components together - every single time you use them. Designers can't simply write HTML like syntax - Someone has to step in and put some javascript bindings in there - which then makes the maintenance harder. I think the idea makes sense for overriding default behavior, but default behaviors should be supported. And defaults would require knowing either your parent, or who your owner is.
There are a number of benefits to not doing this, the main two are: reusability and encapsulation.
Let's say our RadioButton has this public interface:
<RadioButton active={true} onSelect={function(event){}}>text</RadioButton>
We could construct another component called SuperRadioButton, which might have a different way of presenting itself, but still have the same public api as RadioButton, so it's a valid child of RadioButtonGroup.
If we're accessing the parent, then the parent's internals become part of the public api of these components, and we need to be much more careful with how we change our code, because a change in any of these components could cause the entire application to break.
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