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)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay