How to check if the parent component is a specific component?
Asked Answered
C

2

6

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?

Concussion answered 5/11, 2015 at 10:8 Comment(0)
C
2

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

Cordless answered 5/11, 2015 at 13:16 Comment(1)
Thank you for your answer. I use your first approach at the moment (just give the item a href attribute and it will turn into a link). I don't want to create two seperate components, because I'm using Semantic UI. There, the item in the menu uses the same classes (ui and item) as for other items othside the menu. Only the used html tag changes the rendering of those items. So, even if this is a bad example and you should use a seperate component, is there no way to access the parent form inside another component to check its class? Maybe handy for other components.Concussion
P
1

Another way to do this without passing props is to use a context.

The Menu parent would provide this context, and the Item would consume it - if a value is present, that'd mean the Item is being rendered inside a Menu and otherwise inside a div.

Plauen answered 17/9 at 3:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.