reactjshierarchy

How to check if the parent component is a specific component?


I'm pretty new to ReactJS, but I'm slowly getting behind it.

I want to create a smart component, it should detect if it is "inside" another component and render differently then.

Example:

<Menu>
  <Item />
</Menu>

Here, the item component should render as an anchor.

If used inside any other component or a div, it should simply render as a div as well.

Is there an easy way to check, if a component is inside another component in React?


Solution

  • You could solve this by passing a prop, saying something about the context the component is being used in.

    The simplest solution in your case would be to, whenever you use the item component in menu, you pass a prop.

    render(){
      <Menu>
        <Item insideMenu={true} />
      </Menu>
    }
    

    Then inside the render you have two different return statements (depending on the insideMenu-prop).

    // Item.jsx
    render() {
      if(this.props.insideMenu)
        return (whatever)
    
      return (whateverElse)
    }
    

    Normally I wouldn't reccomend this though. Components, in my opinion, should be reuseable and generic if possible. In this case, I'd argue it would be better to have two components: Item and MenuItem. So then it would be

    <Menu>
      <MenuItem>
    </Menu>
    
    <AnythingElse>
      <Item>
    </AnythingElse>
    

    Inside MenuItem, you may very well use the Item component as well, if they share the same behaviour. So in that case, MenuItem would render Item, as well as the extra behaviour required for the menu. Or simply wrap it inside an anchor-tag, if that's all there is to it.

    Either solution works, but the latter is (in my opinion) cleaner. Less surprises, easier to read, and less that can go wrong (no need to juggle props).