Reuse different React components to create new ones
Play on CodeSandbox
npm i reuse
Thanks to @eldargab for the package name on npm.
This enables (sub)atomic design approach.
When using classic CSS, we have a powerful way to compose "stylesheet components" by applying multiple class names to our HTML elements (
.rounded etc.). But, by doing that in React, which has its own component structure, we'll have conflicting component structures.
The component returned by the
use factory will expect a
import use from "reuse";const Box = ;<Box />; // null<Box ="div" />; // <div /><Box = />; // <Link />
You can create the component with a default element:
const Box = ;<Box />; // <div /><Box ="span" />; // <span />
You can create the component with another component. Just make sure to render the
use prop as the underlying element and pass the other props down (at least, when
use isn't a string – HTML element):
import React from "react";import use from "reuse";// grab the `use` prop and pass down other propsconst Base = use: T = "div" ...props <T />;const Box = ;<Box />; // <div /><Box ="span" />; // <span />const BoxSpan = ;<BoxSpan />; // <span />
You can use
Baseto filter custom props when
useis a string using @emotion/is-prop-valid, for example.
Let's create some components:
// Using styled-componentsconst Paper = `box-shadow: 0 2px 4px rgba(0, 0, 0, 0.30);`;// Using class namesconst Rounded =;// Using inline stylesconst Button =;
Once you have a few of those components, you can combine them using the same
import use from "reuse";import Rounded Paper Button from "../components";// with factoryconst RoundedPaperButton = ;<RoundedPaperButton />; // <button style="..." class="..." /><RoundedPaperButton ="div" />; // <div style="..." class="..." />// with prop<Rounded = /> // <button style="..." class="..." /><Rounded = /> // <div style="..." class="..." />
Note that the underlying HTML element will always be based on the last component you pass to
How does this compare to render props and HOCs?
These are equivalent implementations:
<Paper><Rounded ><Button ><button >Button</button></Button></Rounded></Paper>
;// or<Paper = />
When using render props or HOCs, you have to stick with their static (HOC) or dynamic implementation (render prop). With Reuse, besides simplicity, you can use both depending on your needs.
MIT © Haz