Last active
October 18, 2016 10:16
-
-
Save i-van/78347a3a19461614baa571d4218d2f64 to your computer and use it in GitHub Desktop.
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 * 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