Git Product home page Git Product logo

macro-components's Introduction

macro-components

Create flexible layout and composite UI components without the need to define arbitrary custom props.

Build Status

npm i macro-components
import React from 'react'
import styled from 'styled-components'
import Macro from 'macro-components'
import { space, fontSize, color } from 'styled-system'

// Define some styled-components
const Box = styled.div`${space} ${fontSize} ${color}`
Box.displayName = 'Box'

const Image = styled.img`
  max-width: 100%;
  height: auto;
  ${space}
`
Image.displayName = 'Image'

const Heading = styled.h2`${space} ${fontSize} ${color}`
Heading.displayName = 'Heading'

const Text = styled.div`${space} ${fontSize} ${color}`
Text.displayName = 'Text'

// create a macro function with the UI components you intend to use
const macro = Macro({
  Image,
  Heading,
  Text
})

// Create a macro-component
const MediaObject = macro(({
  Image,
  Heading,
  Text
}) => (
  <Flex p={2} align='center'>
    <Box width={128}>
      {Image}
    </Box>
    <Box>
      {Heading}
      {Text}
    </Box>
  </Flex>
))
import MediaObject from './MediaObject'

// get the macro component's child components
const { Image, Heading, Text } = MediaObject

// Use the macro-component by passing the components as children
const App = props => (
  <div>
    <MediaObject>
      <Image src='kitten.png' />
      <Heading>
        Hello
      </Heading>
      <Text>
        This component keeps its tree structure but still allows for regular composition.
      </Text>
    </MediaObject>
  </div>
)

Features

  • Single component creator
  • Intended for use with libraries like styled-components & glamorous
  • Encapsulate layout structure in composable components
  • Help keep your component API surface area to a minimum
  • Works with any other React components

Note: Macro components are intended to only work with specific child components. If you're wanting to define slots, see the Alternatives section below.

Motivation

Often it's best to use React composition and props.children to create UI that is composed of multiple elements, but sometimes you might want to create larger composite components with encapsulated tree structures for layout or create Bootstrap-like UI components such as panels, cards, or alerts. This library lets you create composite components with encapsulated DOM structures without the need to define arbitrary props APIs and that work just like any other React composition.

This can help ensure that your component API surface area remains small and easier to maintain.

If you find yourself creating composite React components that don't map to data structures, as described in Thinking in React, then this module is intended for you.

Usage

Macro(componentsObject)(elementFunction)

Returns a React component with a composable API that keeps tree layout structure.

const Banner = Macro({
  // pass a components object
  Heading,
  Subhead
})(({
  // the element function receives child elements
  // named according to the components object
  Heading,
  Subhead
}) => (
  <Box p={3} color='white' bg='blue'>
    {Heading}
    {Subhead}
  </Box>
)

The elementFunction argument is called with an object of elements based on the componentsObject passed to the Macro function. Using the Banner component above would look something like the following.

import Banner from './Banner'

const App = () => (
  <Banner>
    <Banner.Heading>Hello</Banner.Heading>
    <Banner.Subhead>Subhead</Banner.Subhead>
  </Banner>
)

componentsObject

The components object is used to defined which components the macro component will accept as children.

elementFunction

The element function is similar to a React component, but receives an elements object as its first argument and props as its second one. The elements object is created from its children and is intended to make encapsulating composition and element structures easier.

Within the macro component, the element function is called with the elements object and props: elementFunction(elementsObject, props).

// example
const elFunc = ({ Heading, Text, }, props) => (
  <header>
    {Heading}
    {Text}
  </header>
)

const Heading = styled.h2``
const Text = styled.div``

const componentsObj = {
  Heading,
  Text
}

const SectionHeader = Macro(componentsObj)(elFunc)

Omitting children

For any element not passed as a child to the macro component, the element function will render undefined and React will not render that element. This is useful for conditionally omitting optional children

const macro = Macro({ Icon, Text, CloseButton })

const Message = macro({
  Icon,
  Text,
  CloseButton
}) => (
  <Flex p={2} bg='lightYellow'>
    {Icon}
    {Text}
    <Box mx='auto' />
    {CloseButton}
  </Flex>
)
import Message from './Message'

const { Text, CloseButton } = Message

// Omitting the Icon child element will render Message without an icon.
const message = (
  <Message>
    <Text>{props.message}</Text>
    <CloseButton
      onClick={props.dismissMessage}
    />
  </Message>
)

Props passed to the root component

The second argument passed to the element function allows you to pass props to the root element or any other element within the component.

const macro = Macro({ Image, Text })

const Card = macro(({
  Image,
  Text
}, props) => (
  <Box p={2} bg={props.bg}>
    {Image}
    {Text}
  </Box>
))
// example usage
<Card bg='tomato'>
  <Card.Image src='kittens.png' />
  <Card.Text>Meow</Card.Text>
</Card>

Clone Component

To apply default props to the elements passed in as children, use the Clone component in an element function.

import Macro, { Clone } from 'macro-components'
import { Heading, Text } from './ui'

const macro = Macro({ Heading, Text })

const Header = macro(({ Heading, Text }) => (
  <Box p={2}>
    <Clone
      element={Heading}
      fontSize={6}
      mb={2}
    />
    <Clone
      element={Text}
      fontSize={3}
    />
  </Box>
))

Using a Component Multiple Times

To use the same component twice, give it a unique key in the componentsObject.

import React from 'react'
import Macro from 'macro-components'
import { Heading } from './ui'

const macro = Macro({
  Heading: Heading,
  Subhead: Heading
})

const Header = macro(({ Heading, Subhead }) => (
  <Box p={2}>
    {Heading}
    {Subhead}
  </Box>
))
<Header>
  <Header.Heading>Hello</Header.Heading>
  <Header.Subhead>Subhead</Header.Subhead>
</Header>

Alternatives

To create layout components that are not coupled to specific child components, using props or ordered children is probably a simpler approach.

The solutions below allow you to pass any arbitrary components as props or children.

See this discussion for more.

// using custom props
const MyLayout = ({
  left,
  right
}) => (
  <Flex>
    <Box width={128}>
      {left}
    </Box>
    <Box width={1}>
      {right}
    </Box>
  </Flex>
)

<MyLayout
  left={(
    <Image src='kitten.png' />
  )}
  right={(
    <Text>Meow</Text>
  )}
/>
// using ordered children
const Header = props => {
  const [ first, second ] = React.Children.toArray(props.children)
  return (
    <Box p={3}>
      {first}
      {second}
    </Box>
  )
}

<Header>
  <Heading>First</Heading>
  <Text>Second</Text>
</Header>
// using a children object
const Header = ({
  children: {
    left,
    right
  }
}) => (
  <Flex>
    <Box>
      {left}
    </Box>
    <Box width={1}>
      {right}
    </Box>
  </Flex>
)

<Header>
  {{
    left: (
      <Image src='kitten.png' />
    ),
    right: (
      <Text>Meow</Text>
    )
  }}
</Header>

Related

MIT License

macro-components's People

Contributors

jxnblk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

macro-components's Issues

Failed prop type: Invalid child component `[object Object]`. Must be one of: Cover, Body, Footer

I'm using Theme UI with the pragma set in .babelrc like this:

{
  "presets": [["next/babel", {
    "preset-react": {
      "pragma": "jsx"
    }
  }]],
  "plugins": [
    [
      "@emotion/babel-plugin-jsx-pragmatic",
      {
        "module": "theme-ui",
        "import": "jsx",
        "export": "jsx"
      }
    ]
  ]
}

and I'm creating the following macro component:

import React from "react";
import Macro from "macro-components";
import Flex from "../Flex";
import Box from "../Box";
import Stack from "../Stack";

const Cover = ({ children }) => (
  <Box
    sx={{
      borderBottom: "thin",
      borderColor: "muted",
    }}
  >
    {children}
  </Box>
);

const Body = ({ children }) => <Stack gap={3}>{children}</Stack>;

const Footer = ({ children }) => <Box mt="auto">{children}</Box>;

const Card = Macro({ Cover, Body, Footer })(
  ({ Cover, Body, Footer }, props) => (
    <Flex
      sx={{
        bg: "bg",
        border: "thin",
        borderColor: "muted",
        borderRadius: "base",
        flexDirection: "column",
      }}
      {...props}
    >
      {Cover}
      <Stack height="100%" p={4} gap={4}>
        {Body}
        {Footer}
      </Stack>
    </Flex>
  )
);

export default Card;

but then I'm trying to use it in the app I see the error:

Failed prop type: Invalid child component `[object Object]`. Must be one of: Cover, Body, Footer

I'm wondering if this is somehow related...

Relying on function.name is brittle

I think relying on fn.name makes the API very brittle.
The function name can (and usually does!) change during minification.

I understand .dispayName or explicitly specifying it as a "fake name prop" works as a more reliable fallback but I don’t think most people will be aware unless you force this. The name prop is also problematic because components might accept a legitimate name prop, and the API clobbers it.

Apologies if I misunderstood the API!

(Note: I know it says in the README to set displayName. But most people won't because it works without that in DEV.)

RFC: Explicit API

After a discussion in #3 I think I have a better idea of what you're aiming at.
Here's a proposal of how we could change the API. I think it allows us to:

  • Remove the requirement of specifying displayName
  • Remove the caveat that built-in .name will get minified (and thus broken)
  • Allow components with name property and don't overload it with custom meaning
  • Actually enforce that only the allowed components get rendered

The main idea of the proposal is that since the "macro" component knows which children it allows, it should just put them on itself as fields. Then we don't have to "guess" which component corresponds to which "slot" by its name because the mapping is explicit.

Rewritten README examples with the proposed API:

import React from 'react'
import styled from 'styled-components'
import macro from 'macro-components'
import { space, fontSize, color } from 'styled-system'

// Define some styled-components
const Box = styled.div`${space} ${fontSize} ${color}`
const Heading = styled.h2`${space} ${fontSize} ${color}`
const Text = styled.div`${space} ${fontSize} ${color}`

// Create a macro-component
const MediaObject = macro(
  // Define "slots" => "components" map
  { Image, Heading, Text },
  // Define where to render them
  ({ Image, Heading, Text }) => (
    <Flex p={2} align='center'>
      <Box width={128}>
        {Image}
      </Box>
      <Box>
        {Heading}
        {Text}
      </Box>
    </Flex>
));

// ----------------------------------
// The code below will typically be in another file
// ----------------------------------

// Use the macro-component by passing the components as children
const { Image, Heading, Text } = MediaObject;

const App = props => (
  <div>
    <MediaObject>
      <Image src='kitten.png' />
      <Heading>
        Hello
      </Heading>
      <Text>
        This component keeps its tree structure but still allows for regular composition.
      </Text>
    </MediaObject>
  </div>
)

Note how there are two changes:

  • macro first argument is now a mapping from the "slot name" to a component. With ES6 shorthand syntax it's super concise.
  • You need to reference types from the "macro" component itself, not manually.

This solution is versatile. Here is the second example:

const Banner = macro(
  { Heading, Subhead },
  ({ Heading, Subhead }) => (
  <Box p={3} color='white' bg='blue'>
    {Heading}
    {Subhead}
  </Box>
)
const { Heading, Subhead } = Banner;
<Banner>
  <Heading>Hello</Heading>
  <Subhead>Subhead</Subhead>
</Banner>

You can always be even more explicit too if you prefer this style:

<Banner>
  <Banner.Heading>Hello</Banner.Heading>
  <Banner.Subhead>Subhead</Banner.Subhead>
</Banner>

But what if we want to have multiple elements of the same type? No name prop, we just customize the mapping.

const Banner = macro(
  {
    Heading,
    // The slot called "Subhead" also holds a Heading
    Subhead: Heading
  },
  ({ Heading, Subhead }) => (
  <Box p={3} color='white' bg='blue'>
    {Heading}
    {Subhead}
  </Box>
)
const { Heading, Subhead } = Banner;
<Banner>
  <Heading>Hello</Heading>
  <Subhead>Subhead</Subhead>
</Banner>

There is no need for a special API to use the component type. It is already enforced automatically.

I hope this makes sense!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.