Question

How to implement components like Sidebar or Dialog that represent generic "boxes" which may *contain* anything?

#react

Answer

In general, composition is preferred over inheritance. React allows to solve the "containment" problem by using the special children prop to pass children elements directly into their output:

function FancyBorder(props) {
  // Assigning multiple CSS classes to the same element
  // works like in HTML, i.e. by separating the class names
  // by spaces
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

https://reactjs.org/docs/composition-vs-inheritance.html#containment

Learn

Author

xavi

Reviews
Last
next

Students 1