Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eslint: Problem with default props in functional component (Typescript - React)

What I have

import { NextPage } from 'next';
import React from 'react';

interface Props {
  name: string;
  gretting?: string; // Error: ESLint: propType "gretting" is not required, but has no corresponding defaultProps declaration.(react/require-default-props) 
}

const Hello: React.FunctionComponent<Props> = ({ name, gretting = 'night' }: Props) =>
  <p>Hi {name} Good {gretting}</p>;

const Home: NextPage = () => <Hello name="Jhon Doe" />;

export default Home;

Problem

Eslint react plugin complain with this error ESLint: propType "gretting" is not required, but has no corresponding defaultProps declaration.(react/require-default-props).

According with this answer the approach used to defaultProps with default parameters values its fine so what is the best way to solve this issue? Use Hello.defaultProps = {} or turn off the rule react/require-default-props? there is a better approach?.

like image 713
Cristian Flórez Avatar asked Sep 01 '20 23:09

Cristian Flórez


People also ask

Why default props is not working in react?

Default props are only used if no value is passed for the prop. It is is shallow merge, not a deep merge. From the docs (emphasis mine): The result of getDefaultProps() will be cached and used to ensure that this.

Are default props deprecated?

Default values. And because Dan says defaultProps will be deprecated from React, which is the only reason we use them to begin with.

What is default props in react?

Default props can be used to define any props that you want to be set for a component, whether or not a value is actually passed in from the parent component. When using default props, you can still override the values specified in the default props object when you pass in values from the parent component.


2 Answers

I found another solution for functional components - you can just use React.FC, which provides type checking and autocomplete for static properties like defaultProps.

const Hello: React.FC<{name: string, gretting: string}> = ({ name, gretting = 'night' }) =>

In that case you don't have to use interface at all. But in case you want for some reason:

const Hello: React.FC<IProps> = ({ name, gretting = 'night' }) =>

===== UPDATE=====

Additionally:

"react/prop-types": "off" // Since we do not use prop-types

"react/require-default-props": "off" // Since we do not use prop-types

like image 190
enk1 Avatar answered Oct 03 '22 20:10

enk1


I've had this problem and fixed it by exporting the type or interface, though I can't explain why that was the solution to the issue.

export interface Props {
  name: string;
  greeting?: string;
}

const Hello = ({name, greeting = 'Hi'}: Props): JSX.Element = {}

edit: found you need Typescript 3.0 as per this answer: https://stackoverflow.com/a/51486735/5059401

like image 35
ricom Avatar answered Oct 03 '22 19:10

ricom