Search code examples
javascriptreactjsfrontendreact-propsweb-frontend

Is it possible in React to define which prop to pass (and whether to pass) to child components based on prop from parent component?


Basically imagine the following situation, there are 4 existing components: MainComponent1, MainComponent2, IntermediateComponent and ChildComponent. MainComponent1 and MainComponent2 can use IntermediateComponent as their child component, and ChildComponent is a child component for IntermediateComponent.

Depending on which component is a parent component to IntermediateComponent the props that are being passed to the ChildComponent by IntermediateComponent can be either 1 out of 2 options, or there could be a case that some prop would be only applicable to MainComponent1's descendant (as to indirect child through IntermediateComponent).

Is it possible to set up with React to setup something like this:

/* IntermediateComponent */

<ChildComponent
  color="primary"
  {mainProp === 'MAIN2' ? variant="contained" : variant="outlined"}>
   Example Title
</ChildComponent>

OR

<ChildComponent
  color="primary"
  {mainProp === 'MAIN2' ? variant="contained" : undefined}>
   Example Title
</ChildComponent>

I know that the following setup will not work, so please look at it as rather pseudocode, but basically what I'm trying to achieve is that depending on the value of one prop (mainProp) that is being passed from the MainComponent1 or MainComponent2 to determine whether some prop (variant in this case) that is being passed to the ChildComponentshould have a particular value or should not be even passed.

I'm trying to combine 2 components in the app right now, which are similar in overall in structure but have to be passing different props to child components. What could be a better solution to implement such thing?


Solution

  • What about simply setting value conditionally:

    <ChildComponent
      color="primary"
      variant={mainProp === 'MAIN2' ? 'contained' : undefined}
    >
       Example Title
    </ChildComponent>
    

    If things get more complicated you can always spread out:

    <ChildComponent
      color="primary"
      ...(mainProp === 'MAIN2' ? { a: 10, b: 11 } : { y: 123 })
    >
       Example Title
    </ChildComponent>
    

    this will either add a=10 and b=11 or y=123