1

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.

1
  • If you don't want to use If-Else, you could consider switch... Commented Jun 19, 2020 at 15:39

1 Answer 1

2

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" />
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for replying!Im new to web develpment. Can u please tell me what does those three dots mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.