Skip to content

Instantly share code, notes, and snippets.

@eddyw
Last active November 1, 2017 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddyw/2a70ef1a2fcaaeea837c3a73976f510e to your computer and use it in GitHub Desktop.
Save eddyw/2a70ef1a2fcaaeea837c3a73976f510e to your computer and use it in GitHub Desktop.
Suck less at React (utilities #1): Switch Components
import React from 'react'
import propTypes from 'prop-types'
import SwitchWhen from './SwitchWhen'
class SwitchIf extends React.PureComponent {
static propTypes = {
test: propTypes.any.isRequired,
equals: propTypes.any,
children: props => (
React.Children
.toArray(props.children)
.some(Component => (
![SwitchIf, SwitchWhen].includes(Component.type)
))
? new Error('children must be an instance of SwitchWhen or SwitchIf')
: null
),
}
static defaultProps = {
children: null,
equals: undefined,
}
render() {
const { children, test } = this.props
return React.Children
.toArray(children)
.find(Component => Component.props.equals === test) || null
}
}
export default SwitchIf
import React from 'react'
import propTypes from 'prop-types'
class SwitchWhen extends React.Component {
static propTypes = {
equals: propTypes.any.isRequired,
render: propTypes.node.isRequired,
}
render() {
return this.props.render
}
}
export default SwitchWhen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment