-1

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?

Konstantink1
  • 575
  • 1
  • 8
  • 26
  • 1
    Yes you can try this Example Title – lost_in_magento Sep 03 '21 at 15:09
  • 1
    Does this answer your question? [React.js -- How to pass properties object to child component?](https://stackoverflow.com/questions/20913288/react-js-how-to-pass-properties-object-to-child-component) – iunfixit Sep 03 '21 at 15:13

1 Answers1

1

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

Newbie
  • 4,462
  • 11
  • 23