Tuesday, July 19, 2022

Default props in React function components

Having default props in a React component is a rather common situation. The most popular way to accomplish this is to pass the default values to a defaultProps property on the function component. However, this property will be deprecated in the future.

Spoiler: due to the sheer amount of code written with it, it never will be deprecated. It’s more likely that a warning will show in the console.

Anyway, in order to keep things clean and guard from this future warning, I came up with a clean pure TypeScript solution to this problem:

interface Props {
	name: string;
	surname?: string;
	age?: number;
}

const defaultProps = {
	surname: 'Doe',
};

function MyComponent(propsNonDef: Props) {
	const props = {...defaultProps, ...propsNonDef};

	return <div>{props.surname}</div>;
}

The code above provides the correct behavior and proper TypeScript validation. It ended becoming an answer on StackOverflow.

No comments: