DEV Community

Timothy Fosteman
Timothy Fosteman

Posted on • Updated on

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!

Top comments (0)