DEV Community

Timothy Fosteman
Timothy Fosteman

Posted on • Edited on

3 1

Component Composition & Inheritance in React

Component Composition

Whenever UI component renders it's children, props.children are interpolated inside tags:

const Bar = props => (
    <div className={'ui items ' + props.color}>
        {props.children}
    </div>
);
Enter fullscreen mode Exit fullscreen mode

Children can be anything: text, expressions, elements, components

...
const NavigationBar = props => (
    <Bar>
        My Bar Element! //text

        {props.items[Math.floor(Math.random() * props.items.length)]} //expression

        <a className="link">
            Anchor element
        </a>

        <Link>
            Custom component <Link>
        </Link>
    </Bar>
);
Enter fullscreen mode Exit fullscreen mode

Inner contents of Bar are evaluated before NavigationBar is rendered.

Note, that React elements like <Bar /> and <NavigationBar /> are not dissimilar to that of <div /> or <a /> elements since library and Babel will transpile JSX down to ES5 for compatibility concerns.

Why Not Component Inheritance?

Creation of component inheritance hierarchies may find it's use in reusable non-UI components, however, a functional component is better off extracted into separate JavaScript module.

Thank you for reading!

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs