React: A panel that wraps its children

Wrapper components use children to hold any content. Build one that the rest of an app can reuse.

What to build

A panel component that frames any content with a title and a style variant.

Requirements

  • Write Panel with the props title, variant (default info) and children. It renders a section with the class panel panel-VARIANT, an h3 with the title, and a div with the class panel-body containing the children.
  • App renders three panels: Tip (default variant) containing a p Save your work often.; Warning with the variant warning containing a ul of two li Battery low and Unsaved changes; and Done with the variant success containing a p All tests passed.

Constraints

The panel must not know what its children are.

Example

The preview shows three framed panels titled Tip, Warning and Done, with their content inside.

Why it works

children lets the panel hold a paragraph, a list or anything else, so the frame and its style are written once and the content is decided by each user of the component.

Hints

Hint 1

function Panel({ title, variant = "info", children }) places children in a div with the class panel-body.

Hint 2

Build the class name from the variant: "panel panel-" + variant.

Solution

Show one correct solution (try it yourself first)
function Panel({ title, variant = "info", children }) {
  return (
    <section className={"panel panel-" + variant}>
      <h3>{title}</h3>
      <div className="panel-body">{children}</div>
    </section>
  );
}

export default function App() {
  return (
    <div>
      <Panel title="Tip">
        <p>Save your work often.</p>
      </Panel>
      <Panel title="Warning" variant="warning">
        <ul>
          <li>Battery low</li>
          <li>Unsaved changes</li>
        </ul>
      </Panel>
      <Panel title="Done" variant="success">
        <p>All tests passed.</p>
      </Panel>
    </div>
  );
}

Lesson: Props: passing data to components →