'Head script application/ld+json in nextjs triggers ESLint: Cannot read property '0' of undefined
I have some code similar to this. I need to add application/ld+json structured data, but doing it like so, triggers this ESLint error:
ESLint: Cannot read property '0' of undefined and it refers to scriptStringProduct prop. Even if I only generate that code if that variable is not undefined, I get this error.
How to fix it?
import Head from 'next/head';
import { IHeadTags } from '../../../utils/types';
export const Index: React.FC<IHeadTags> = (props: IHeadTags) => {
scriptStringProduct = { __html: '' },
isProduct = false
} = props;
return (
<Head>
{isProduct && scriptStringProduct !== undefined && (
<script
type='application/ld+json'
dangerouslySetInnerHTML={scriptStringProduct ?? { __html: '' }}
key='scriptStringProduct-jsonld'
/>
)}
</Head>
);
};
export default Index;
Solution 1:[1]
Inside your .eslintrc.json file you need to turn off the rule for next-script-for-ga.
Example:
// .eslintrc.json
{
"settings": {
"react": {
"version": "detect"
}
},
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"next",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["react", "@typescript-eslint"],
"rules": {
"react/prop-types": "off",
"react/react-in-jsx-scope": "off",
"@typescript-eslint/no-explicit-any": "off",
"@next/next/no-document-import-in-page": "off",
"@next/next/next-script-for-ga": "off" // make sure to have this rule off
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabriel Arghire |
