Skip to content Skip to sidebar Skip to footer

React Render Various Components Based On Three Logic Paths

I am really struggling to get my head around how to render specific components based on logical markers when there are more than two. Usually I'd write something like render() {

Solution 1:

Since your questions is about more than 2 and not just 3 components then this is a great place to use a map like so. No switch, no if's and it's performant.


let colorComponents = {
    'blue': <Blue />
    'green': <Green />
    'red': <Red/>
    'yellow': <Yellow />
}

render() { // Can pass null or what ever fallback component you prefer
    return colorComponents[myData.colour] || null;
}


Solution 2:

You can move the checks to inside the render but before the return. So you can do something like this:

const colour = myData.colour;
let content;

if (isBlue) {
   content = <Blue />
} else if (isRed) {
   content = <Red />
} else {
   content = <Green />
}

return <div>{content}</div>

You can also refactor this to a switch based on colour.


Solution 3:

do chaining like this

let isBlue = 'blue';

console.log( isBlue == 'red' ? 'red': isBlue == 'blue' ? 'blue' : isBlue == 'green' ? 'green' : 'none'  )

Solution 4:

you can do something like that based on two condition

const colour = myData.colour;

 render() {
    return isBlue ? <Blue /> : isGreen ? <Green /> : <Red />;
}

Solution 5:

Try something like this.

const colour = myData.colour;


render() {
    return (
       {colour.Blue?  <Blue />}
        /* or */
       {colour.Green? <Green />}
        /* or */
       {colour.Red? <Red /> }
    );
}

Post a Comment for "React Render Various Components Based On Three Logic Paths"