DEV Community

Cover image for Open-Closed Principle in React
Mikhael Esa
Mikhael Esa

Posted on • Updated on

Open-Closed Principle in React

Open-Closed Principle

Software entities should be open for extension, but closed for modification.

Open-closed gif

Open for extension means that you should be able to add new functionality or features to a React component without having to change its existing code.

Closed for modification Once a React component is designed and implemented, you should avoid making direct changes to its source code whenever possible.

const Book = ({ title, image, type, onClickFree, onClickPremium }: IBook) => {
  const handleReadPremium = () => {
    // Some logic
    onClickPremium();
  };

  const handleReadFree = () => {
    // Some logic
    onClickFree();
  };
  return (
    <div>
      <img src={image} />
      <p>{title}</p>
      {type === "Premium" && (
        <button onClick={handleReadPremium}>Add to cart +</button>
      )}
      {type === "Free" && <button onClick={handleReadFree}>Read</button>}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

The code above violates this principle as there is a type check to render out a specific feature.

If there is a new book type, then there would be a further modification of this component as well. Let's fix it!

const Book = ({ title, image, children }: IBook) => {
  return (
    <div>
      <img src={image} />
      <p>{title}</p>
      {children}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

We get rid of the unecessary codes and create a new props which is children so the other component can extend this component by passing it as a children.

// We extend Book component to create a new component
const PremiumBook = ({ title, image, onClick }: IBook) => {
  return (
    <Book title={title} image={image}>
      <button onClick={onClick}>Add to cart +</button>
    </Book>
  );
};

const FreeBook = ({ title, image, onClick }: IBook) => {
  return (
    <Book title={title} image={image}>
      <button onClick={onClick}>Read</button>
    </Book>
  );
};
Enter fullscreen mode Exit fullscreen mode

This way, your Book component will be Open for extension and Closed for modificationđź‘Ť

What's next?

Let's not stop here since there are 3 more principles left to learn in SOLID which I will cover in the next article so stay tuned.

Top comments (0)