添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

React Component with TypeScript

by Robin Wieruch
- Edit this Post

When using in React, we may want to type their with TypeScript. Overall there are two ways of making a React component type safe with TypeScript, however, let's start by converting the following JavaScript React component to a TypeScript React component as leading example:

const Select = ({ label, value, options, onChange }) => {
return (
<label>
{label}
<select value={value} onChange={onChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</label>
);
};

The straightforward yet most verbose way of typing this React component would be inlining the types in the functional component's function signature:

const Select = ({
label,
value,
options,
onChange,
}: {
label: string;
value: string;
options: { label: string; value: string }[];
onChange: (event: React.ChangeEvent<HTMLSelectElement>) => void;
}) => {
return (
<label>
{label}
<select value={value} onChange={onChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</label>
);
};

From there, we would start extracting reusable types from the functional component's function signature into a standalone TypeScript type. It's up to you whether you prefer using a type or interface:

type Option = { label: string; value: string };
type Options = Option[];
const Select = ({
label,
value,
options,
onChange,
}: {
label: string;
value: string;
options: Options;
onChange: (event: React.ChangeEvent<HTMLSelectElement>) => void;
}) => {
return (
<label>
{label}
<select value={value} onChange={onChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</label>
);
};

Since React props are just a JavaScript object, we can extract a type respectively to the React function component's props too:

type Option = { label: string; value: string };