DEV Community

loading...

Component Composition & Inheritance in React

fosteman profile image Timothy Fosteman Updated on ・1 min read

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>
);

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>
);

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!

Discussion

pic
Editor guide