Nikhil Goyal
Nikhil Goyal

Reputation: 1973

Render one of the children based on condition

I am trying to create a switch HOC for conditional rendering which behaves like a switch statement in ReactTS

<Switch>
    <Case condition={cond1}>
        Hello
    </Case>
    <Case condition={cond2}>
        World
    </Case>
    <Default>
         Hi stranger
    </Default>
</Switch>

If the cond1 is true, render "Hello".
If the cond1 is false but cond2 is true, render "World".
If both conditions are false, render "Hi stranger".

Upvotes: 4

Views: 923

Answers (1)

Nikhil Goyal
Nikhil Goyal

Reputation: 1973

I created three files in JS once to test and everything is working fine.

Switch.js

class Switch extends React.Component {
  getComponentToRender() {
    return React.Children.toArray(this.props.children).find(function (child) {
      if (child.type.name === "Case") {
        if (child.props.condition) {
          return true;
        }
      }
      if (child.type.name === "Default") {
        return true;
      }
      return false;
    });
  }

  render() {
    return this.getComponentToRender();
  }
}

export default Switch;

Case.js -> Need to make sure that this component gets condition as boolean.

export default function(props) {
  return props.children;
}

Default.js

export default function(props) {
  return props.children;
}

Using the above files as

<Switch>
        <Case condition={false}>Hello</Case>
        <Case condition={false}>World</Case>
        <Default>Hi</Default>
      </Switch>

Upvotes: 2

Related Questions