Skip to content

Instantly share code, notes, and snippets.

@i-van
Last active October 18, 2016 10:16
Show Gist options
  • Save i-van/78347a3a19461614baa571d4218d2f64 to your computer and use it in GitHub Desktop.
Save i-van/78347a3a19461614baa571d4218d2f64 to your computer and use it in GitHub Desktop.
import * as React from 'react';
interface ISelectProps {
value?: string;
options: SelectOption[];
placeholder?: string;
onChange?: (value: SelectOption) => void;
}
interface ISelectState {
value: string;
}
type SelectOption = {
value: string;
label: string;
}
export class Select extends React.Component<ISelectProps, ISelectState> {
defaultProps: ISelectProps = {
value: '',
options: [],
placeholder: '',
onChange: () => {}
};
constructor (props: ISelectProps) {
super(props);
this.state = {
value: this.props.value
};
}
public render(): React.ReactElement<{}> {
const { value } = this.state;
const { options, placeholder } = this.props;
return (
<select value={value} onChange={this.onChange}>
{placeholder && <option value="" disabled>{placeholder}</option>}
{
options.map(({ value, label }: SelectOption) => (
<option key={value} value={value}>
{label}
</option>
))
}
</select>
);
}
private onChange = (event: Event) => {
const { onChange, options } = this.props;
const value = (event.target as HTMLSelectElement).value;
this.setState({ value });
onChange(options.find((option: SelectOption) => option.value === value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment