react/require-default-props
Require a default value for every prop that is not required
An optional prop that the parent leaves out is undefined in the component. With a default for each optional prop, the component never needs to handle that case, and the defaults show what happens if a prop is missing.
By default the rule looks for the default in defaultProps. React 19 ignores defaultProps on function components, so set functions to "defaultArguments" there.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"react/require-default-props" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"react/require-default-props" = ["error", {
functions = "defaultProps", # "defaultArguments", "defaultProps" or "ignore"
classes = "defaultProps", # "defaultProps" or "ignore"
forbidDefaultForRequired = false,
ignoreFunctionalComponents = false,
}]Examples#
example.jsx1 problem
function Greeting({ name, punctuation }) {
return <h1>Hello {name}{punctuation}</h1>;
}
Greeting.propTypes = {
name: PropTypes.string.isRequired,
punctuation: PropTypes.stringpropType punctuation is not required, but has no corresponding defaultProps declaration.,
};example.jsxNo problems
function Greeting({ name, punctuation }) {
return <h1>Hello {name}{punctuation}</h1>;
}
Greeting.propTypes = {
name: PropTypes.string.isRequired,
punctuation: PropTypes.string,
};
Greeting.defaultProps = {
punctuation: "!",
};Options#
| Option | Default | What it does |
|---|---|---|
functions | "defaultProps" | Where a function component sets its defaults: "defaultProps", "defaultArguments" (in the destructured parameter), or "ignore" to skip function components. |
classes | "defaultProps" | "ignore" skips class components. |
forbidDefaultForRequired | false | Also report a default in defaultProps for a required prop. |
ignoreFunctionalComponents | false | An older way to write functions: "ignore". |
With "defaultArguments", the defaults belong in the destructured parameter. The rule then reports defaultProps on a function component, and a default for a required prop.
example.tsxwith
{ "functions": "defaultArguments" }1 problemtype Props = { name: string; punctuation?: string };
function Greeting({ name, punctuationpropType punctuation is not required, but has no corresponding default argument value. }: Props) {
return <h1>Hello {name}{punctuation}</h1>;
}example.tsxwith
{ "functions": "defaultArguments" }No problemstype Props = { name: string; punctuation?: string };
function Greeting({ name, punctuation = "!" }: Props) {
return <h1>Hello {name}{punctuation}</h1>;
}With forbidDefaultForRequired:
example.jsxwith
{ "forbidDefaultForRequired": true }1 problemfunction Greeting({ name }) {
return <h1>Hello {name}</h1>;
}
Greeting.propTypes = {
name: PropTypes.string.isRequiredpropType name is required and should not have a defaultProps declaration.,
};
Greeting.defaultProps = {
name: "world",
};