Composition over inheritance in React

Reusing component by having a Wrapper class in React

·

2 min read

The reuse principle

Composition over inheritance (or composite reuse principle) is a OOP design pattern to reuse the composition (e.g classes that have been implemented with functionality) rather then using inheritance.

Example

Let say you have 3 sections of data, which are:

  • Section 1: Display bio information
  • Section 2: Display address information
  • Section 3: Display contact information

Screenshot 2022-02-18 at 10.24.37 PM.png

You want a default rounded corner and shadow for all of them. And so, you create a wrapper class called Card. [Composition pattern]

Note that you have to pass in props.className and props.children to include the child's CSS style and props.

import './Card.css';

const Card = (props) => {
    const classes = 'card ' + props.className;
    return (
        <div className={classes}>
            {props.children}
        </div>
    );
}

In Card.css, we define the border-radius and the box shadow.

.card {
    border-radius: 12px;
    box-shadow: 0 1px 8px rgba(0, 0, 0, 0.25);
}

Card component will then be able to use it to wrap around other components, which includes all CSS style and props of the children.

const Biodata = () =>
{
  return (
    <Card className="bio-title">Bio data here</Card>
  );
}
const AddressData = () =>
{
  return (
    <Card className="address-title">Address data here</Card>
  );
}
const ContactData = () =>
{
  return (
    <Card className="contact-title">Contact data here</Card>
  );
}
class App extends React.Component {
  render() {
    return (
      <div>
        <Biodata/>
        <AddressData/>
        <ContactData/>
      </div>
    );
  }
}

And done! All three of them will have fancy rounded corner and box shadow!

Screenshot 2022-02-18 at 10.31.11 PM.png

Try it out in codepen here! codepen.io/yipcode/pen/eYeVvbN