Home > Software design >  React ESLint error at line that doesn't exist
React ESLint error at line that doesn't exist

Time:03-20

I'm using nextjs and when i run next build it fails and gives the error below. The error points me to line 19 (which is an empty line) and line 33 (which doesn't even exist?).

For the error message itself, I saw an issue with eslint-plugin-react which has supposedly been fixed recently, but I'm still getting the error with the newest updated version in package-lock.json:

"eslint-plugin-react": ">=7.29.4",

I have also tried deleting the .next folder and doing next build again, and deleting node-modules and doing npm install, the error still happens.

File with the error:

import Subtitle1 from './subtitle-1'
import Subtitle2 from './subtitle-2'

class SwitchSubtitle extends Component {
    constructor(...args) {
      super(...args);
      this.state = {
        stitles: [<Subtitle1/>, <Subtitle2/>],
        index: 0
      };
    }
  
    componentDidMount() {
      this.timer = setInterval(() => {
        this.setState({index: this.state.index   1})
      }, 3500)
    }
  
    render() {
      const { index, stitles } = this.state;
      return(
          <p>{stitles[index % 2]}</p>
      );
    }
}

export default SwitchSubtitle

Error given from next build:

info  - Checking validity of types

Failed to compile.

./components/landing/switchSubtitle.js
9:19  Error: Missing "key" prop for element in array  react/jsx-key
9:33  Error: Missing "key" prop for element in array  react/jsx-key

CodePudding user response:

When you render an array of components each element needs a key that’s unique within the array.

You’re effectively rendering such an array here:

stitles: [<Subtitle1/>, <Subtitle2/>]

You could add keys, like this:

stitles: [<Subtitle1 key=“1”/>, <Subtitle2 key=“2”/>]

But I think a better approach would be to put the components themselves in the array and defer rendering until it’s needed. This way you’re only rendering the component that’s actually being displayed:

stitles: [Subtitle1, Subtitle2]

// …

const Cmp = stitles[index % 2];

return (
   …
   <Cmp />
   …
)

CodePudding user response:

I think that in this case the error is a little missleading, what it propably means is that you just simple need to pass a key to this component(assuming your mapping it)

Try adding key to p element

  return(
      <p key={index}>{stitles[index % 2]}</p>
  );

CodePudding user response:

I don't think you nead the array stitles as state, the fact that the index is being incremented and the state being changed and the render function being trigged is enough, why don't you try this :

return(
   {index%2 == 0 ? (
     ....
     <Subtitle1/>
     ...
   ) : (
     ...
     <Subtitle2/>
     ...
   )}
);
  • Related