• Stars
    star
    1,681
  • Rank 27,769 (Top 0.6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

😎 Compose render props components like a pro

😎 React Adopt - Compose render props components like a pro

GitHub release Build Status Codacy Badge

📜 Table of content

🧐   Why

Render Props are the new hype of React's ecosystem, that's a fact. So, when you need to use more than one render props component together, this can be boring and generate something called a "render props callback hell", like this:

Bad

💡   Solution

  • Small. 0.7kb minified!
  • Extremely Simple. Just a method!

React Adopt is a simple method that composes multiple render prop components, combining each prop result from your mapper.

📟   Demos

💻   Usage

Install as project dependency:

$ yarn add react-adopt

Now you can use React Adopt to compose your components. See below for an example using the awesome react-powerplug:

Good

Working with new Context api

One use case that React Adopt can fit perfectly is when you need to use React's new context api that use render props to create some context:

import React from 'react'
import { adopt } from 'react-adopt'

const ThemeContext = React.createContext('light')
const UserContext = React.createContext({ name: 'John' })

const Context = adopt({
  theme: <ThemeContext.Consumer />,
  user: <UserContext.Consumer />,
})

<Context>
  {({ theme, user }) => /* ... */}
</Context>

See this demo for a better explanation.

Custom render and retrieving props from composed

Some components don't use the children prop for render props to work. For cases like this, you can pass a function instead of a jsx element to your mapper. This function will receive a render prop that will be responsible for your render, the props passed on Composed component, and the previous values from each mapper. See an example:

import { adopt } from 'react-adopt'
import MyCustomRenderProps from 'my-custom-render-props'

const Composed = adopt({
  custom: ({ render }) => <MyCustomRenderProps render={render} />
})

<Composed>
  {({ custom }) => (
    <div>{custom.value}</div>
  )}
</Composed>

You can also retrieve the properties passed to the composed component this way too:

import { adopt } from 'react-adopt'
import { Value } from 'react-powerplug'

const Composed = adopt({
  greet: ({ initialGreet, render }) => (
    <Value initial={initialGreet}>{render}</Value>
  )
})

<Composed initialGreet="Hi">
  {({ greet }) => (
    <div>{greet.value}</div>
  )}
</Composed>

And get previous mapper results as prop for compose:

import { adopt } from 'react-adopt'

import { User, Cart, ShippingRate } from 'my-containers'

const Composed = adopt({
  cart: <Cart />,
  user: <User />,
  shippingRates: ({ user, cart, render }) => (
    <ShippingRate zipcode={user.zipcode} items={cart.items}>
      {render}
    </ShippingRate>
  )
})

<Composed>
  {({ cart, user, shippingRates }) => /* ... */ }
</Composed>

Mapping props from mapper

Sometimes, get properties from your mappers can be kind of boring depending on how nested the result from each mapper. To easily avoid deeply nested objects or combine your results, you can map the final results into a single object using the mapProps function as the second parameter.

import { adopt } from 'react-adopt'
import { Value } from 'react-powerplug'

const mapper = {
  greet: <Value initial="Hi" />,
  name: <Value initial="John" />,
}

const mapProps = ({ greet, name }) => ({
  message: `${greet.value} ${name.value}`,
})

const Composed = adopt(mapper, mapProps)

const App = () => (
  <Composed>
    {({ message }) => /* ... */}
  </Composed>
)

You can do that using the <Adopt /> component as well:

import { Adopt } from 'react-adopt'
import { Value } from 'react-powerplug'

const mapper = {
  greet: <Value initial="Hi" />,
  name: <Value initial="John" />,
}

const mapProps = ({ greet, name }) => ({
  message: `${greet.value} ${name.value}`,
})

const App = () => (
  <Adopt mapper={mapper} mapProps={mapProps}>
    {({ message }) => /* ... */}
  </Adopt>
)

Using components on mapper

If you want to use your component directly as mapper value you can do that. Some nice thing here is that all non-react static methods of your components will be hoisting for composed component:

import { React } from 'react'
import { adopt } from 'adopt'
import { Value } from 'react-powerplug'

const Greeter = ({ render, name }) => render(`Hi ${name.value}`)

Greeter.sayHi = (name) => `Hi ${name}`

const Composed = adopt({
  name: <Value name="John" />
  greet: Greet
})

console.log(Composed.sayHi('John')) // Hi John

const App = () => (
  <Composed>
    {({ greet, name }) => /* ... */ }
  </Composed>
)

Leading with multiple params

Some render props components return multiple arguments in the children function instead of a single one (see a simple example in the new Query and Mutation component from react-apollo). In this case, you can do an arbitrary render with render prop using your map value as a function:

import { adopt } from 'react-adopt'
import { Mutation } from 'react-apollo'

const ADD_TODO = /* ... */

const addTodo = ({ render }) => (
  <Mutation mutation={ADD_TODO}>
    {/* this is an arbitrary render where you will pass your two arguments into a single one */}
    {(mutation, result) => render({ mutation, result })}
   </Mutation>
)

const Composed = adopt({
  addTodo,
})

const App = () => (
  <Composed>
    {({ addTodo: { mutation, result } }) => /* ... */}
  </Composed>
)

See this demo for a complete explanation about multiple params..

Typescript support

React Adopt has full typescript support when you need to type the composed component:

import * as React from 'react'
import { adopt } from 'react-adopt'
import { Value } from 'react-powerplug'

interface RenderProps {
  foo: { value: string }
}

interface Props {
  tor: string
}

const foo = ({ tor, render }) => (
  <Value initial="foo">{render}</Value>
)

const Composed = adopt<RenderProps, Props>({
  foo,
})

<Composed tor="tor">
  {({ foo, bar }) => (
    <div>{foo.value}</div>
  )}
</Composed>

Inline composition

If you dont care about typings and need something more easy and quick, you can choose to use an inline composition by importing the <Adopt> component and passing your mapper as a prop:

import React from 'react'
import { Adopt } from 'react-adopt'
import { Value } from 'react-powerplug'

const mapper = {
  greet: <Value initial="Hi" />,
  name: <Value initial="John" />
}

<Adopt mapper={mapper}>
  {({ greet, name }) => /* ... */}
</Adopt>

🕺   Contribute

  1. Fork this repository to your own GitHub account and then clone it to your local device
  2. Install dependencies using Yarn: yarn install
  3. Make the necessary changes and ensure that the tests are passing using yarn test
  4. Send a pull request 🙌

More Repositories

1

reworm

🍫 the simplest way to manage state
TypeScript
1,464
star
2

micro-router

🚉 A tiny and functional router for Zeit's Micro
JavaScript
621
star
3

react-video

🎞 React component to load video from Vimeo or Youtube across any device.
JavaScript
273
star
4

react-simpletabs

Just a simple tabs component built with React
JavaScript
188
star
5

algorithms-with-es6

Just a bunch of algorithms using Javascript with ES6
JavaScript
161
star
6

reicons

💅 Bundle your SVG into a fully customized React components
JavaScript
113
star
7

gatsby-starter-docz

📝 Gatsby starter with Docz and a blog for your documentation
JavaScript
90
star
8

frontend-styleguide

Keep your code clean, legible and beautiful!
CSS
69
star
9

spacefold

Use Pub/Sub pattern inside your React applications easily
TypeScript
61
star
10

oneoften

Tips, tricks, tutoriais and many things about "How building a Large Scale application with Javascript"
44
star
11

yarn-workspaces-example

Sample monorepo project using new Yarn feature called Workspaces
JavaScript
41
star
12

which-licenses-i-have

📝 Learn about the licenses around your package
JavaScript
29
star
13

docz-plugin-react-native

Plugin that allow you to use React Native with docz
JavaScript
21
star
14

storz

Global state machines in an easy way
TypeScript
21
star
15

shazam

⚡️ An opinionated and usefull react app management
JavaScript
17
star
16

hacker-news-es6

Hacker News feed built with ECMAScript 6 and jQuery
JavaScript
17
star
17

vitejs-boilerplate

ViteJS boilerplate with TailwindCSS, React Router v6, Typescript and more.
TypeScript
15
star
18

libundler

JavaScript
14
star
19

nextjs-boilerplate

NextJS boilerplate with some cool stack
TypeScript
12
star
20

promiseJS.br

Tradução do site http://www.promisejs.org/
CSS
11
star
21

certifyJS

NodeJS module that generate a course certificate in PDF
JavaScript
9
star
22

eleicoes2022

Estudos analítico encima dos dados do TSE sobre o resultado das Eleições 2022 no Brasil
7
star
23

notion-todo

Todo app made using the Notion API
JavaScript
6
star
24

xresource

TypeScript
6
star
25

reason-todo-example

Just a simple todo app built with ReasonML
OCaml
5
star
26

to-titlelize

NodeJS module to format string in titlelize
JavaScript
4
star
27

pedronauck.com

My website 🔥
JavaScript
3
star
28

jarvis

Central de conteúdo sobre desenvolvimento da GoNorth
2
star
29

builder-skeleton

Just a test for Stackblitz api
HTML
2
star
30

create-dataset

Experiment recreating React Context using plain Javascript
JavaScript
2
star
31

nvim

My current Neovim configuration
Lua
2
star
32

typescript-with-docz-example

Just a simple test
TypeScript
2
star
33

react-grocery-list

This is a sample Grocery List application to test ReactJS + Gulp + Browserify
JavaScript
2
star
34

xstate-fp

Just another approach to write state machines for XState
1
star
35

zmk-config

My zmk configuration
1
star
36

fusebox-preact-example

Sample application using FuseBox and Preact
JavaScript
1
star
37

docz-plugin-svgr

Use svgr as loader for svg images
TypeScript
1
star
38

teste-repo

Teste de repositório
1
star
39

datocms-blog-demo-5245

JavaScript
1
star
40

astronvim_config

Astro vim config
Lua
1
star
41

mediator

Mediator pattern applied on React
TypeScript
1
star
42

csb-xut4hw

HTML
1
star