react-composite

1.0.0 • Public • Published

React Composite

Wrap components without adding an element to the DOM.

Description

Use Composite when you want to return more than one child and you don't need additional element around children.

In React > 16 Component may return more then one child components by returning an array. Downside is that you don't write "pure" JSX and you have to worry about component keys. You can wrap your children with a html element but you get an additional and unnecessary layer.

To avoid both array pattern and html element wrapper use Composite component. It allows you to wrap children without need to define keys and it doesn't add an element to the dom.

Composite component is a pass-through, it just pass children down the chain leaving React "core" to take care of the rest.

Examples

Multiple children

  • without Composite (HTML element wrapper)
// Without Composite
const Username = () => (
    <div>
        <span>User: </span>
        <span>MrBr</span>
    </div>
);
// DOM
// <div>
//  <span>User: </span>
//  <span>MrBr</span>
// </div>
  • with Composite
const Username = () => (
    <Composite>
        <span>User: </span>
        <span>MrBr</span>
    </Composite>
);
 
// DOM
// <span>User: </span>
// <span>MrBr</span>

Children as Function pattern

  • without Composite (with Array pattern)
const Username = () => (
    <GetUsername>
        {(username) => [
            <span key="label">User: </span>,
            <span key="username">{username}</span>
        ]}
    </GetUsername>
);
  • with Composite
const Username = () => (
    <GetUsername>
        {(userName) => (
            <Composite>
                <span>User: </span>
                <span>{userName}</span>
            </Composite>
        )}
    </GetUsername>
);

Readme

Keywords

Package Sidebar

Install

npm i react-composite

Weekly Downloads

2

Version

1.0.0

License

MIT

Last publish

Collaborators

  • mr_br