const Component: FC<Props> = ({ foo = 'hello', bar = 'world' }) => {
The reason that code like this is recommended is because it's convenient. It's a nice shortcut for:
const Component: FC<Props> = (props) => {
const foo = props.foo === undefined ? 'hello' : props.foo;
const bar = props.bar === undefined ? 'world' : props.bar;
But if you have something else you want to do, you can write different code. You say in the comments you want to have a predefined defaultProps object, which then gets applied to the missing props. That can be done like this (among other possibilities):
const defaultProps = {
foo: 'hello',
bar: 'world',
}
const Component: FC<Props> = (props) => {
const propsWithDefaults = {
...defaultProps,
...props,
}
const { foo, bar } = propsWithDefaults;
Playground link
If you want typescript to check the defaultProps object to make sure it doesn't have typos or extra properties and such, you can make use of the satisfies keyword (introduced in Typescript 4.9):
const defaultProps = {
fo: 'hello', // <--- oops, typo
bar: 'world',
baz: 'so' // <--- oops, extra property
} satisfies Partial<Props>
Playground link
Answer from Nicholas Tower on Stack OverflowReact 18 warning defaultProps will be removed from function components
Design decision: keep defaultProps for functional components
React - Override Default Props
How to declare nested default props as it's now deprecated ?
Videos
Hi,
on a new project I have this warning :
"Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead."
But I can't figure out how should I do to declare the default value ?
Here is one of my component that have nested props :
const TextInput = ({ options, label, input }: TextInputProps) => {// logic here}And I typed it like this :
export type TextInputProps = {
options?: {
withLabel?: boolean
defaultLabelClass?: boolean
defaultInputClass?: boolean
}
label: {
label: string
className?: string
}
input: {
type: string
name: string
for: string
id: string
className?: string
placeholder?: string
required?: boolean
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
}
}
export const TextInputDefaultProps = {
options: {
withLabel: true,
defaultLabelClass: true,
defaultInputClass: true,
},
label: {
className: undefined,
},
input: {
className: undefined,
placeholder: undefined,
required: false,
onChange: undefined,
},
}I did try something like this but it does not work:
const TextInput = ({
options: { withLabel = true, defaultLabelClass = true, defaultInputClass = true },
label: { label = 'Label', className = undefined },
input: { type = 'text', name = 'input', id = 'input', placeholder = 'Placeholder', className = undefined , onChange = undefined},
}) => {So how are we suppose to deal with nested props ?
Thanks :)