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

Build Your Own Forms without Manual Coding

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

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more