Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Created October 25, 2018 08:29
Show Gist options
  • Save LeeCheneler/e52b8cfbf8b242200bf3eb82cfcc4f0c to your computer and use it in GitHub Desktop.
Save LeeCheneler/e52b8cfbf8b242200bf3eb82cfcc4f0c to your computer and use it in GitHub Desktop.
Example of compound component in React
import React, { Component } from 'react'
import Radio from './Radio'
class Example extends Component {
state = {
value: null
}
onChange = value => {
this.setState(prevState => ({ ....prevState, value }))
}
const render = () => (
<Radio.Group name="nums" onChange={this.onChange} value={this.state.value}>
<Radio.Button id="one" value="one">one</Radio.Button>
<Radio.Button id="two" value="two">two</Radio.Button>
<Radio.Button id="three" value="three">three</Radio.Button>
</Radio.Group>
)
import React, { Fragment } from 'react'
import T from 'prop-types'
const Button = ({ children, id, value, ...props }) => (
<Fragment>
<input type="radio" id={id} value={value} {...props} />
<label htmlFor={id}>{children}</label>
</Fragment>
)
Button.propTypes = {
children: T.node.isRequired,
id: T.string.isRequired,
value: T.string.isRequired
}
const Group = ({ children, name, onChange, value }) =>
React.Children.map(children, child =>
React.cloneElement(child, {
...child.props,
name,
checked: value === child.props.value,
onChange: e => {
onChange(e.target.value)
}
})
)
Group.propTypes = {
children: T.node.isRequired,
name: T.string.isRequired,
onChange: T.func.isRequired,
value: T.string
}
Group.defaultProps = {
value: null
}
export default {
Button,
Group
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment