I would like to create a React component in Typescript that has all the same attributes as the HTML <select>
element.
How would I type this?
type Props = {
label: string
} & HTMLSelectElementAttributes; // This one is wrong
function MySelect(props: Props) {
return <label>{props.label}</label><select {...props}>
<option value="A">A</option>
<option value="B">B</option>
</select>;
}
CodePudding user response:
In a type-aware IDE like VSCode, if you hover over the <select
, you'll see:
React.DetailedHTMLProps<React.SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>
You can use that as the type for the other props.
type Props = {
label: string;
} & React.DetailedHTMLProps<React.SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>; // This one is wrong
const MySelect = (props: Props) => (
<div>
{' '}
<label>
label
{props.label}
</label>
<select {...props} />
</div>
);
// Example usage in which no type warnings result
const X = () => <MySelect label="foo" onChange={() => { console.log('change'); }} />;