1

In React, is there a recommended or industry-standard technique for conditionally rendering different component types that have the same props and innerHTML?

To be specific I'm swapping between <Text /> and <TextInput /> in React Native.

I would check state, if blah is true then render <ComponentA />, else <ComponentB />. However they'll take identical props/innerText.

As an example:

Not DRY

var component = <CoolComponent quantity="42" color="green" write="true">some stuff</CoolComponent>;
if (true) {
  component = <ADifferentOne quantity="42" color="green" write="true">some stuff</ADifferentComponent>;
} else if (false) {
  <ANewComponent quantity="42" color="green" write="true">some stuff</ANewComponent>
}

The best solution I've found is:

var TagType = CoolComponent;
if (true) {
  TagType = ADifferentOne;
} else if (false) {
  TagType = ANewComponent
}
<TagType quantity="42" color="green" write="true">Some stuff</TagType>;
asparism
  • 604
  • 1
  • 8
  • 17

2 Answers2

3

You could extract it to the dedicated component if you'd prefer to. Just use ternary operator & spread object for this case

const NewComponent = ({ props }) => (
  your_condition ?
    <ADifferentOne {...props} /> :
    <ANewComponent {...props} />
)
Alex Antonov
  • 14,134
  • 7
  • 65
  • 142
1
const ComponentSwitcher = ({ props }) => {
  return props.if ? <props.onTrue {...props} /> : <props.onFalse {...props} />
}

Usage:

<ComponentSwitcher if={myVar} onTrue={ADifferentOne} onFalse={ANewComponent
} quantity="42" color="green" write="true">some stuff</ComponentSwitcher>
Stackia
  • 2,110
  • 17
  • 23