Reuse different React components to create new ones
Play on CodeSandbox
Installation
npm i reuse
Thanks to @eldargab for the package name on npm.
Why
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 (.btn
, .large
, .rounded
etc.). But, by doing that in React, which has its own component structure, we'll have conflicting component structures.
Reuse solves it by combining React components together as if they were CSS classes. This also means that not only style will be composed, but also JavaScript behavior, like React lifecycle methods and event handlers.
Usage
Reuse simply exports a factory method that returns a React component. You can leverage that method in two ways: augmentation and combination.
Examples
Augmentation
The component returned by the use
factory will expect a use
prop:
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
Base
to filter custom props whenuse
is a string using @emotion/is-prop-valid, for example.
Combination
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 use
methods:
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 use
.
FAQ
How does this compare to render props and HOCs?
These are equivalent implementations:
Render props
<Paper> <Rounded > <Button > <button >Button</button> </Button> </Rounded> </Paper>
High-order components
;
Reuse
;// 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.
License
MIT © Haz