Search code examples
reactjscomponentsreact-propsconditional-rendering

Displaying component based on prop value react


I have four components Rectangle, Circle, Triangle, Star. Based on the value that the user gave in props I want to return the component. For example, If the user gave a prop as a Rectangle, I want to display the Rectangle Component. I don't want to use the If-Else statement every time checking for all four conditions. Is there a better option?

Ex: Rectangle Component

import React from "react";

function Rectangle(props) {
  return (
    <div className="term">
      <svg width="400" height="110">
        <rect
          width="300"
          height="100"
          stroke="black"
          stroke-width="3"
        />
      </svg>
    </div>
  );
}

export default Rectangle;

Can anybody please help? Thanks in advance.


Solution

  • Define a static mapping for shape type -> Component. E.g. assuming the shape type is provided in a prop shape:

    const Shapes = {
        rectangle: Rectangle,
        circle: Circle,
        triangle: Triangle,
        star: Star,
    };
    
    const Shape = ({shape, ...props}) => {
        const ActualShape = Shapes[shape];
    
        return <ActualShape {...props} />;
    };
    

    Example Usage:

    <Shape shape="circle" r="10" stroke="red" />
    <Shape shape="rectangle" stroke="black" width="300" height="100" />