Search code examples
javascriptreactjseslinteslint-config-airbnb

Object Destructuring eslint throws react/prop-types


export const Top = (props) => {

    return (
        <div key={props.id} className={props.borderColor}>
            <div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
                <p className="text-xl font-bold">{props.title}</p>
...

My code looked so until I read the Airbnb JavaScript Style Guide.

Then I changed it to the following.

export const Top = (props) => {
    const { id, borderColor, title, price, color } = props;
    
    return (
        <div key={id} className={borderColor}>
            <div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
                <p className="text-xl font-bold">{title}</p>

I liked it, but eslint accused me of the following error:

'id' is missing in props validation           react/prop-types

After a short research I came across the following React eslint error missing in props validation

So I have changed my code.

export const Top = () => {
    const { id, borderColor, title, price, color } = this.props;

    return (
        <div key={id} className={borderColor}>
            <div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
                <p className="text-xl font-bold">{title}</p>

The error went away, but then i got this error:

Stateless functional components should not use `this`  react/no-this-in-sfc

Probably not a good solution and I don't use classes.

The Airbnb Guidlines say the following is the best way to go.

function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}

But what if you have more than 2 parameters in the parentheses? I remember this being talked about as bad in the clean code book by robert c martin.

What works well for you? I also don't want to disable any rules, but would like to solve the problem in a clean way.


Solution

  • export const Top = (props) => {
    const { id, borderColor, title, price, color } = props;
    
    return (
        <div key={id} className={borderColor}>
            <div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
                <p className="text-xl font-bold">{title}</p>
    

    This was right. Just you have to do some extra code.

    • Before export block you have to import PropTypes

        import React from 'react';
        import PropTypes from 'prop-types';
      
    • Then after export block you have to add these

      Top.propTypes = {
        id: PropTypes.oneOfType(PropTypes.number, PropTypes.string),
        borderColor: PropTypes.string,
        title: PropTypes.string,
        price: PropTypes.number,
        color: PropTypes.string,
      }
      

    For more details, checkout this link https://reactjs.org/docs/typechecking-with-proptypes.html