Last active
November 1, 2017 14:46
-
-
Save eddyw/2a70ef1a2fcaaeea837c3a73976f510e to your computer and use it in GitHub Desktop.
Suck less at React (utilities #1): Switch Components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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