Skip to content

Instantly share code, notes, and snippets.

@heygema
Last active January 30, 2018 06:27
Show Gist options
  • Save heygema/217bf40bd8070637d233cab9dfbbf84b to your computer and use it in GitHub Desktop.
Save heygema/217bf40bd8070637d233cab9dfbbf84b to your computer and use it in GitHub Desktop.
RadioGroup and RadioItem
// @flow
import React from 'react';
import {RadioItem, RadioGroup} from './Radio';
type P = {};
type S = {};
class App extends React.Component<P, S> {
render() {
return (
<div>
<h1>Radio Color</h1>
<RadioGroup name="favColor">
<RadioItem>Red</RadioItem>
<RadioItem>Green</RadioItem>
<RadioItem>Blue</RadioItem>
</RadioGroup>
<h1>Radio Car</h1>
<RadioGroup name="favCar">
<RadioItem>Mercy</RadioItem>
<RadioItem>BMW</RadioItem>
<RadioItem>Tesla</RadioItem>
</RadioGroup>
</div>
);
}
}
export default App;
// @flow
import React from 'react';
type RadioItemProps = {
name?: string,
children?: string,
};
type RadioGroupProps = {
name: string,
children: Array<RadioItem>,
};
export let RadioGroup = (props: RadioGroupProps) => {
let {children, name} = props;
let childrenWithProps = React.Children.map(children, (RadioItem) => {
return React.cloneElement(RadioItem, {name: name});
});
return <div>{childrenWithProps}</div>;
};
export let RadioItem = (props: RadioItemProps) => {
let {name, children} = props;
return (
<div>
<input type="radio" id={children} name={name} />
<label htmlFor={children}>{children}</label>
</div>
);
};
// @flow
import React from 'react';
import PropTypes from 'prop-types';
type RadioItemProps = {
name?: string,
children?: string,
};
type RadioGroupProps = {
name: string,
children: Array<RadioItem>,
};
export class RadioGroup extends React.Component<RadioGroupProps> {
getChildContext() {
return {name: this.props.name};
}
static childContextTypes = {
name: PropTypes.string,
};
render() {
let {children} = this.props;
return <div>{children}</div>;
}
}
export function RadioItem(props: RadioItemProps, context: Object) {
let {children} = props;
return (
<div>
<input type="radio" id={children} name={context.name} />
<label htmlFor={children}>{children}</label>
</div>
);
}
RadioItem.contextTypes = {
name: PropTypes.string,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment