项目作者: sastan

项目描述 :
render-prop helper to render anything (Functions, Components, Elements, ...)
高级语言: JavaScript
项目地址: git://github.com/sastan/react-render-callback.git
创建时间: 2018-09-06T10:14:25Z
项目社区:https://github.com/sastan/react-render-callback

开源协议:MIT License

下载


react-render-callback

render-prop helper to render anything (Functions, Components, Elements, …)

version
MIT License
module formats: umd, cjs, and es
umd size
umd gzip size

Build Status
Code Coverage
Maintainability
PRs Welcome
Code of Conduct

Sponsored by Kenoxa
Semver
semantic-release
Greenkeeper badge

The problem

You want your component to support the render prop pattern
with different types of values like
Function as children,
a React.Component (Component Injection)
or just plain react elements.

This solution

react-render-callback frees you from detecting what kind fo render prop
your component is dealing with:

  1. import React from 'react'
  2. import renderCallback from 'react-render-callback'
  3. class Component from React.Component {
  4. state = {}
  5. render() {
  6. // can be any prop like render, component, renderHeader, ...
  7. // children may be a function, a component, an element, ...
  8. return renderCallback(this.props.children, this.state)
  9. }
  10. }

View an example in codesandbox.io.

Highlights

Table of Contents

Installation

This module is distributed via npm which is bundled with node and
should be installed as one of your project’s dependencies:

  1. npm install --save react-render-callback

This package also depends on react. Please make sure you
have it installed as well.

The Universal Module Definition (UMD) is available
via unpkg.com and exposed as ReactRenderCallback.

  1. <script src="https://unpkg.com/react-render-callback/dist/react-render-callback.umd.min.js"></script>

Usage

API

renderCallback([ renderable [, props [, options ] ] ])

renders the given renderable with props

  1. // esm
  2. import renderCallback from 'react-render-callback'
  3. // commonjs
  4. const renderCallback = require('react-render-callback')

renderable (optional): anything that can be rendered like a function, a component, or elements

props (optional): to pass to renderable

options (optional):

  • cloneElement (default: false, since: v1.1.0): allows to pass props to
    the element using React.cloneElement
  1. renderCallback(<a href="#bar">bar</a>, {title: 'foo'})
  2. // --> <a href="#bar">bar</a>
  3. renderCallback(<a href="#bar">bar</a>, {title: 'foo'}, {cloneElement: true})
  4. // --> <a href="#bar" title="foo">bar</a>

returns

  • the created react element
  • false, null, undefined and true are returned as null
    just like in JSX
  • the value as is for all other values

createRender([ renderable [, options ] ])

since: v1.1.0

Returns a function ((...args) => ...) to render renderable with.

  1. // esm
  2. import {createRender} from 'react-render-callback'
  3. // commonjs
  4. const {createRender} = require('react-render-callback')

Accepts the same arguments (except props) as renderCallback(). It exists mainly
to pre-determine (read cache) what type renderable is, to prevent these
checks on every invocation.

Additionally the returned method accepts more than one argument (since: v1.2.0).
This allows to provide several parameters to the renderable.

  1. const renderCallback = createRender((a, b, c) => ({a, b, c}))
  2. renderCallback(1, 2, 3)
  3. // -> { a: 1, b: 2, c: 3 }

If the renderable has a defaultProps property only the first parameter is used
and merged with the defaultProps.

returns

a function ((...args) => ...) to render the args

Examples

A basic example showing the most common use cases can be viewed/edited at codesandbox.io.

Use options.cloneElement

Edit

This option allows to pass down props without to need to create a function
within render which merges the defined and provided props.

  1. class CountSeconds extends React.Component {
  2. state = {
  3. value: 0,
  4. }
  5. componentDidMount() {
  6. this.timer = setInterval(() => {
  7. this.setState(({value}) => ({value: value + 1}))
  8. }, 1000)
  9. }
  10. componentWillUnmount() {
  11. clearInterval(this.timer)
  12. }
  13. render() {
  14. const {children, render = children} = this.props
  15. return renderCallback(render, this.state, {cloneElement: true})
  16. }
  17. }
  18. const DisplayValue = ({prefix = '', value}) => `${prefix}${value}`
  19. const App = ({prefix}) => (
  20. <CountSeconds>
  21. <DisplayValue prefix={prefix} ></DisplayValue>
  22. </CountSeconds>
  23. )

Use createRender to pass down several arguments

Edit

  1. class CountSeconds extends React.Component {
  2. state = {
  3. value: 0,
  4. }
  5. reset = () => {
  6. this.setState({value: 0})
  7. }
  8. componentDidMount() {
  9. this.timer = setInterval(() => {
  10. this.setState(({value}) => ({value: value + 1}))
  11. }, 1000)
  12. }
  13. componentWillUnmount() {
  14. clearInterval(this.timer)
  15. }
  16. render() {
  17. const {children, render = children} = this.props
  18. return createRender(render)(this.state.value, this.reset)
  19. }
  20. }
  21. const DisplayValue = ({prefix = '', value}) => `${prefix}${value}`
  22. const App = () => (
  23. <CountSeconds>
  24. {(value, reset) => (
  25. <React.Fragment>
  26. <DisplayValue prefix="Seconds: " value={value} ></DisplayValue>
  27. <button onClick={reset} type="button">
  28. reset
  29. </button>
  30. </React.Fragment>
  31. )}
  32. </CountSeconds>
  33. )

Use createRender to interop with a library which only supports functions as render-prop

Edit

  1. import Toggle from 'react-toggled'
  2. class Toggler extends React.Component {
  3. static defaultProps = {
  4. onLabel: 'Toggled On',
  5. offLabel: 'Toggled Off',
  6. }
  7. render() {
  8. const {on, getTogglerProps, onLabel, offLabel} = this.props
  9. return (
  10. <div>
  11. <button {...getTogglerProps()}>Toggle me</button>
  12. <div>{on ? onLabel : offLabel}</div>
  13. </div>
  14. )
  15. }
  16. }
  17. const ToggleView = createRender(Toggler)
  18. const App = () => <Toggle>{ToggleView}</Toggle>

Other Solutions

Credits

A special thanks needs to go to Kent C. Dodds for his great
video series (
egghead.io,
frontendmasters.com and
youtube.com).
His projects are either used in this project (kcd-scripts)
or are a template for the structure of this project (downshift).
Make sure to subscribe to his newsletter.

Contributors

Thanks goes to these people (emoji key):


Sascha Tandel
💻 📖 🚇 ⚠️ 👀 📝 🐛 💡 🤔 📢

This project follows the all-contributors specification.
Contributions of any kind welcome!

LICENSE

MIT