DEV Community

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

Posted on • Edited on

15 1 1 1 1

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More