React eslint error missing in props validation

I have the next code, eslint throw:

react/prop-types onClickOut; is missing in props validation

react/prop-types children; is missing in props validation

propTypes was defined but eslint does not recognize it.

import React, { Component, PropTypes } from 'react';

class IxClickOut extends Component {
  static propTypes = {
    children: PropTypes.any,
    onClickOut: PropTypes.func,
  };

 componentDidMount() {
    document.getElementById('app')
      .addEventListener('click', this.handleClick);
  }

  componentWillUnmount() {
    document.getElementById('app')
      .removeEventListener('click', this.handleClick);
  }

  handleClick = ({ target }: { target: EventTarget }) => {
    if (!this.containerRef.contains(target)) {
      this.props.onClickOut();
    }
  };

  containerRef: HTMLElement;

  render() {
    const { children, ...rest } = this.props;
    const filteredProps = _.omit(rest, 'onClickOut');

    return (
      <div
        {...filteredProps}
        ref={container => {
          this.containerRef = container;
        }}
      >
        {children}
      </div>
    );
  }
}

export default IxClickOut;

package.json

{
  "name": "verinmueblesmeteor",
  "private": true,
  "scripts": {
    "start": "meteor run",
    "ios": "NODE_ENV=developement meteor run ios"
  },
  "dependencies": {
    "fine-uploader": "^5.10.1",
    "foundation-sites": "^6.2.3",
    "install": "^0.8.1",
    "ix-gm-polygon": "^1.0.11",
    "ix-type-building": "^1.4.4",
    "ix-type-offer": "^1.0.10",
    "ix-utils": "^1.3.7",
    "keymirror": "^0.1.1",
    "meteor-node-stubs": "^0.2.3",
    "moment": "^2.13.0",
    "npm": "^3.10.3",
    "rc-slider": "^3.7.3",
    "react": "^15.1.0",
    "react-addons-pure-render-mixin": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-fileupload": "^2.2.0",
    "react-list": "^0.7.18",
    "react-modal": "^1.4.0",
    "react-redux": "^4.4.5",
    "react-router": "^2.6.0",
    "react-styleable": "^2.2.4",
    "react-textarea-autosize": "^4.0.4",
    "redux": "^3.5.2",
    "redux-form": "^5.3.1",
    "redux-thunk": "^2.1.0",
    "rxjs": "^5.0.0-beta.9",
    "rxjs-es": "^5.0.0-beta.9",
    "socket.io": "^1.4.8"
  },
  "devDependencies": {
    "autoprefixer": "^6.3.6",
    "babel-eslint": "^6.0.4",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.5.0",
    "core-js": "^2.0.0",
    "cssnano": "^3.7.1",
    "eslint": "^2.12.0",
    "eslint-config-airbnb": "^9.0.1",
    "eslint-import-resolver-meteor": "^0.2.3",
    "eslint-plugin-import": "^1.8.1",
    "eslint-plugin-jsx-a11y": "^1.2.2",
    "eslint-plugin-react": "^5.1.1",
    "node-sass": "^3.8.0",
    "postcss-cssnext": "^2.6.0",
    "sasslets-animate": "0.0.4"
  },
  "cssModules": {
    "ignorePaths": [
      "node_modules"
    ],
    "jsClassNamingConvention": {
      "camelCase": true
    },
    "extensions": [
      "scss",
      "sass"
    ],
    "postcssPlugins": {
      "postcss-modules-values": {},
      "postcss-modules-local-by-default": {},
      "postcss-modules-extract-imports": {},
      "postcss-modules-scope": {},
      "autoprefixer": {}
    }
  }
}

.babelrc

{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "whitelist": [
      "es7.decorators",
      "es7.classProperties",
      "es7.exportExtensions",
      "es7.comprehensions",
      "es6.modules"
  ],
  "plugins": ["transform-decorators-legacy"]
}

.eslintrc

{
  "parser": "babel-eslint",
  "extends": "airbnb",
  "rules": {
    "no-underscore-dangle": ["error", { "allow": [_id, b_codes_id] }],
  },
  "settings": {
    "import/resolver": "meteor"
  },
  "globals": {
    "_": true,
    "CSSModule": true,
    "Streamy": true,
    "ReactClass": true,
    "SyntheticKeyboardEvent": true,
  }
}

Upvotes: 266

Views: 588653

Answers (27)

Although this is not a proper solution, it works for me.

To resolve the React esLint error for missing propTypes validation, paste the following code at the top of the file that shows an error and past it as it is with the comment /* -- */:

/* eslint-disable react/prop-types */

This will disable the specific esLint rule for propTypes validation in the file.

Upvotes: -1

Qadir Hassan
Qadir Hassan

Reputation: 79

This solution works for me, I disable the type checking by adding this line of codes in the eslint.config file. "rules": { "react/prop-types": "off" }

Upvotes: 0

Devin Rhode
Devin Rhode

Reputation: 25367

I know this answer is ridiculous, but consider just disabling this rule until the bugs are worked out or you've upgraded your tooling:

/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling

Or disable project-wide in your eslintrc (or .eslintrc.cjs if setup using vite):

"rules": {
  "react/prop-types": "off"
}

Upvotes: 216

Tariq Rashid
Tariq Rashid

Reputation: 1

I was having the same error learning a vite tutorial. I noticed that there were two eslintrc's versions.

One was auto-added by vite and the other I created in the tutorial:

.eslintrc.cjs .eslintrc.json

I deleted the auto-generated one (.cjs) and the error disappeared.

Upvotes: 0

Pavel Fedotov
Pavel Fedotov

Reputation: 885

I keep returning back to this thread for a 100th time, what is absolutely missign is the reliable link to the docs with prop types.

So here it is https://legacy.reactjs.org/docs/typechecking-with-proptypes.html

Some examples:

SectionContainer.propTypes = {
  children: PropTypes.node.isRequired,
};

Explicit prop:

TOCInline.propTypes = {
  toc: PropTypes.array.isRequired,
  indentDepth: 3,
  fromHeading: 1,
  toHeading: 6,
  asDisclosure: false,
  exclude: "",
};
MyApp.propTypes = {
  Component: PropTypes.func.isRequired,
  pageProps: PropTypes.object.isRequired,
};

Upvotes: 1

I recommend you this code block as a reference, since I solved that problem by taking from the eslint-plugin-react explanation in their documentation

// Examples of correct code for this rule:

function Hello({ name }) {
  return <div>Hello {name}</div>;
}
Hello.propTypes = {
  name: PropTypes.string.isRequired
}

var Hello = createReactClass({
  propTypes: {
    name: PropTypes.string.isRequired,
  },
  render: function() {
    return <div>Hello {this.props.name}</div>;
  },
});

// Or in ES6:
class HelloEs6 extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
HelloEs6.propTypes = {
  name: PropTypes.string.isRequired,
};

// ES6 + Public Class Fields (draft: https://tc39.github.io/proposal-class-public-fields/)
class HelloEs6WithPublicClassField extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
  }
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

For your case you can use this line to see if it works for you but it should solve your problem

class IxClickOut extends Component {
  static propTypes = {
    children: PropTypes.node.isRequired,
    onClickOut: PropTypes.func.isRequired,
  };

This documentation directly from eslint-plugin-react explains how to use prop-types.

It shows you the different ways you have created your components.

Disallow missing props validation in a React component definition (react/prop-types)

It worked for me by following this documentation created directly from eslint to solve the problem.

Upvotes: -1

raja sultan
raja sultan

Reputation: 69

Go to .eslintrc.js file add this line inside rules object

"react/prop-types": "off",

.eslintrc.cjs:

.eslintrc.cjs

Upvotes: 6

MD MIRAJUL ISLAM
MD MIRAJUL ISLAM

Reputation: 59

Disabling the react/prop-types ESLint rule

Open Your file: .eslintrc.cjs

and addenter code here

rules: { "react-refresh/only-export-components": [ "warn", { allowConstantExport: true, "react/prop-types": "off" }, ],

Upvotes: -1

Andrew Malik
Andrew Malik

Reputation: 31

Just a real life example with a solution. Put this code inside a function with the problems, update the props names and data types (int, string etc...) according to your code:

    funcname.propTypes = {
    propName1: PropTypes.any,
    propName2: PropTypes.any,
    propName3: PropTypes.any,
  };

Code above will fix the problem under with the {props.style}, {props.question} and {props.answer} in the FAQ arrow function.

    const FAQ = (props) => {
        FAQ.propTypes = {
          style: PropTypes.string,
          question: PropTypes.string,
          answer: PropTypes.string,
        };

        let [show, setShow] = useState(true);
        return (
          <>
            {/* FAQ questions and answers script */}
    
            <div className={`mx-[5vw] border border-gray 
             ${props.style}`}>
              <div
                onClick={() => setShow(!show)}
                className="flex justify-between text-gray duration-500 ease-in-out hover:bg-gray hover:fill-white hover:text-white"
              >
                <p className="m-4 w-full font-inter text-lg font-extrabold">
                  {props.question}
                </p>
                <div className="flex items-center">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    height="40"
                    viewBox="0 -960 960 960"
                    width="40"
                  >
                    <path
                      d={
                        show
                          ? "M480-344 240-584l56-56 184 184 184-184 56 56-240 240Z"
                          : "M480-528 296-344l-56-56 240-240 240 240-56 56-184-184Z"
                      }
                    />
                  </svg>
                </div>
              </div>
              <div
                className={`font-interm p-6 md:text-lg ${show ? "hidden" : "flex"}`}
              >
                {props.answer}
              </div>
            </div>
          </>
        );
      };

Upvotes: 1

therightstuff
therightstuff

Reputation: 1027

For anyone else encountering this issue when using Javascript (as opposed to TypeScript), React-Admin's linter was bombing out on the following:

const MyCustomRow = ({
    record,
    id
}) => {
    // code here
    ...

Even though my IDE's custom linter wasn't happy with the mix-and-match, it made the react linter happy and had no adverse effects:

const MyCustomRow = ({
    record,
    id
}: {
    record: Record<string, unknown>,
    id: string
}) => {
    // code here
    ...

EDIT: I guess I could have used DatagridRowProps (see the body example in the React-Admin docs, that might be the better approach)

The alternative was disabling the eslint rule by adding the following directive to the top of the file:

/* eslint-disable react/prop-types */

Upvotes: -1

pouyada
pouyada

Reputation: 377

In case someone is facing this issue with a function component here is the correct way to eliminate the TS error, without disabling the lint check.

Props = {testId: string}

const ComponentWithChildren: FC<PropsWithChildren<Props>> = (props: PropsWithChildren<Props>) => (
    <>{props.children}</>
));

Upvotes: 0

AndreUdotai
AndreUdotai

Reputation: 61

If you want to solve this problem in the right way without having to disable the rule, then you can do this: (let's call the flagged prop: 'prop')

import PropTypes from 'prop-types';

export default function MyComponent(props) {
  // Your component code here
}

MyComponent.propTypes = {
  prop: PropTypes.string, 
  // Other prop validations can continue from here
};

Note: I am suggesting this example using React-vite set-up

Upvotes: 4

Mushfiqur Rahman
Mushfiqur Rahman

Reputation: 574

I was facing this problem in React JS:18.2.0. After configuring .eslintrc.cjs the problem is solved. Configuration:

module.exports = {
  root: true,
  env: { browser: true, es2020: true },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react/jsx-runtime',
    'plugin:react-hooks/recommended',
  ],
  ignorePatterns: ['dist', '.eslintrc.cjs'],
  parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
  settings: { react: { version: '18.2' } },
  plugins: ['react-refresh'],
  rules: {
    "react/prop-types": "off",
    "react-refresh/only-export-components": [
      "warn",
      { allowConstantExport: true },
    ],
    "react/jsx-uses-react": 2,
    "react/jsx-uses-vars": "error",
  },
}

Upvotes: 0

Vaishnavi Aswale
Vaishnavi Aswale

Reputation: 225

Install prop-types package with- npm i prop-types --save Import it-

import PropTypes from 'prop-types';

Then specify the props, I implemented this way-

Text.propTypes = {
  children: PropTypes.node.isRequired,
};

export default function Text({ children }) {
  return (
    <VStyle className="para">
      <p>{children}</p>
    </VStyle> 
  );
}

Also add this in your eslintrc.json or .js file

"rules": {
    "react/prop-types": "off"
  }

Upvotes: 17

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27495

Another way is:


File: App.js

    ...
        <Component1 key1="abc" />
    ...

File: Component1.js

1 error:

    function Component1 ({ key1 }) {
        console.log('key1', key1);
    }

2 error:

    function Component1 (props) {
        let{ key1 } = props;
        console.log('key1', key1);
    }

3 works:

NOTE: prop instead of props

    function Component1 (prop) {
        let{ key1 } = prop;
        console.log('key1', key1);
    }

Looks like, linter only checks for proper word props, not for prop or like.
It's a solution if you are just getting started or quick prototyping.
For later or large projects, defining proptypes might be better.


Upvotes: 6

benjdan
benjdan

Reputation: 199

On the new version of React and also Next.js, you can simply import PropTypes as follows,

import PropTypes from "prop-types";

and at the bottom of your file add defaultProps and propTypes such as,

Post.defaultProps = {
  posts: "",
};

Post.propTypes = {
  posts: PropTypes.string,
};

export default Post;

It should resolve your eslint warnings.

Upvotes: 7

DamonWu
DamonWu

Reputation: 134

Instead of disable prop-types rule, we can introduce children property as part of component props, eg:

import React, { Component } from 'react';

export default class ErrorBoundary extends Component<{ children: React.ReactNode }> {
  constructor(props: { children: React.ReactNode }) {
    super(props);

    this.state = { error: null, errorInfo: null };
  }

  componentDidCatch(error: Readonly<unknown>, errorInfo: Readonly<unknown>): void {
    this.setState({ error, errorInfo });
  }

  render(): React.ReactElement | React.ReactNode {
    const { children } = this.props;
    const { error, errorInfo } = this.state as Readonly<Record<string, { componentStack: string }>>;

    if (errorInfo)
      return (
        <details>
          <h3>Oops, error detected.</h3>
          <p>{error?.toString()}</p>
          <p>{errorInfo?.componentStack}</p>
        </details>
      );
    return children;
  }
}

Above one is typical example of getting eslint error gone ~~

Don't worry be happy ~~

Upvotes: 0

Sunnyok
Sunnyok

Reputation: 469

Duplicating my answer from a similar question: https://stackoverflow.com/a/69199304/4290193

eslint-plugin-react@^7.25.0 appears to have resolved the issue for those using React.FC<IProps> with react/prop-types validation rule.

So instead of

const Example: React.FC<IProps> = (props: IProps) => ...

This now works without warnings after the update

const Example: React.FC<IProps> = (props) => ...

Upvotes: 2

edencorbin
edencorbin

Reputation: 2949

I'm finding eslint to be overly strict in the project I'm working on myself but for this error I fixed it by defining my interface and then implementing as such:

interface myInterface: {
  test: string
}

const MyComponent: React.FC<myInterface> = (props: myInterface) => {

Upvotes: 2

Like
Like

Reputation: 141

PropTypes checking is a good thing, not recommend to ignore by settings

You can auto generate the propTypes by using vscode React PropTypes Generate extension:

  1. Select your Component's name
  2. Press command + . (Windows is Ctrl + .) show Code Actions and select PropTypesGenerate, or press shift + command + alt + P (Windows is shift + ctrl + alt + P) in the macOS
  3. Input propType to replace default type

Upvotes: 4

thatguy1155
thatguy1155

Reputation: 102

Functional React component. Defined as object. I got this error because I copied and pasted the object from a different with a slightly different name and forgot to change the name of the proptypes object.

FooterIcons.propTypes = {} -> FooterIcon.propTypes

Upvotes: 0

Siphenathi
Siphenathi

Reputation: 571

For me, upgrading eslint-plugin-react to the latest version 7.21.5 fixed this

Upvotes: 4

airvine
airvine

Reputation: 731

I ran into this issue over the past couple days. Like Omri Aharon said in their answer above, it is important to add definitions for your prop types similar to:

SomeClass.propTypes = {
    someProp: PropTypes.number,
    onTap: PropTypes.func,
};

Don't forget to add the prop definitions outside of your class. I would place it right below/above my class. If you are not sure what your variable type or suffix is for your PropType (ex: PropTypes.number), refer to this npm reference. To Use PropTypes, you must import the package:

import PropTypes from 'prop-types';

If you get the linting error:someProp is not required, but has no corresponding defaultProps declaration all you have to do is either add .isRequired to the end of your prop definition like so:

SomeClass.propTypes = {
    someProp: PropTypes.number.isRequired,
    onTap: PropTypes.func.isRequired,
};

OR add default prop values like so:

SomeClass.defaultProps = {
    someProp: 1
};

If you are anything like me, unexperienced or unfamiliar with reactjs, you may also get this error: Must use destructuring props assignment. To fix this error, define your props before they are used. For example:

const { someProp } = this.props;

Upvotes: 26

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27495

Issue: 'id1' is missing in props validation, eslintreact/prop-types

<div id={props.id1} >
    ...
</div>

Below solution worked, in a function component:

let { id1 } = props;

<div id={id1} >
    ...
</div>

Hope that helps.

Upvotes: 5

Omri Aharon
Omri Aharon

Reputation: 17064

You need to define propTypes as a static getter if you want it inside the class declaration:

static get propTypes() { 
    return { 
        children: PropTypes.any, 
        onClickOut: PropTypes.func 
    }; 
}

If you want to define it as an object, you need to define it outside the class, like this:

IxClickOut.propTypes = {
    children: PropTypes.any,
    onClickOut: PropTypes.func,
};

Also it's better if you import prop types from prop-types, not react, otherwise you'll see warnings in console (as preparation for React 16):

import PropTypes from 'prop-types';

Upvotes: 137

the problem is in flow annotation in handleClick, i removed this and works fine thanks @alik

Upvotes: 2

Konstantin
Konstantin

Reputation: 25369

It seems that the problem is in eslint-plugin-react.

It can not correctly detect what props were mentioned in propTypes if you have annotated named objects via destructuring anywhere in the class.

There was similar problem in the past

Upvotes: 23

Related Questions