Is there a way in ReactJS for a component to find out who it's parent is?
EDIT 1: Regardless of the merits of doing this, is there a way?
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.
EDIT 2: So it's not possible?
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.