Tom
Tom

Reputation: 83

Destructuring props in ReactJS

I have a problem troubleshooting EsLint error
ESLint: Must use destructuring props assignment (react/destructuring-assignment).
The linter requires destructuring the props, but if I do that, I get an undefined parameter.
In my code, I am trying to get a parameter from a URL. What am I doing wrong?

Here I indicate what parameters should be in the URL:

<Route path="/confirm-register/:userName?" component={ConfirmRegistrationPage} />

My original code, it works as expected, the userName parameter gets a string value:

strong textconst ConfirmRegistrationPage = (props) => {
  const { userName } = props.match.params;
  return (
    <>
      <h1>Congratulations, {userName}! </h1>
    </>
  );
};

What I have tried. In this case, userName is undefined:

strong textconst ConfirmRegistrationPage = ({ userName }) => {
  return (
    <>
      <h1>Congratulations, { userName }! </h1>
    </>
  );
};

eslint settings:

{
  "env": {
    "browser": true,
    "commonjs": true,
    "es6": true
  },
  "extends": [
    "plugin:react/recommended",
    "plugin:react/jsx-runtime",
    "eslint-config-airbnb"
  ],
  "parserOptions": {
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 11
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "react/jsx-filename-extension" : "off",
    "react/prop-types": "off",
    "import/no-named-as-default": "off",
    "import/no-named-as-default-member": "off",
    "react/jsx-one-expression-per-line": "off"
  }
}

Upvotes: 1

Views: 2476

Answers (1)

Ivan Popov
Ivan Popov

Reputation: 696

Edit props destructuring. I would choose the first variant. Its more readable.

// first variant 
strong textconst ConfirmRegistrationPage = ({ match }) => {
    const { userName } = match.params
    return (
        <>
            <h1>Congratulations, { userName }! </h1>
        </>
    );
};

// second variant
strong textconst ConfirmRegistrationPage = ({ match: { params: { userName } } }) => {
    return (
        <>
            <h1>Congratulations, { userName }! </h1>
        </>
    );
};

// third variant
strong textconst ConfirmRegistrationPage = ({ match: { params } }) => {
    const { userName } = params
    return (
        <>
            <h1>Congratulations, { userName }! </h1>
        </>
    );
};

Upvotes: 2

Related Questions