I have a React project and I have created a custom hook using the hook useNavigate that comes with the React router v6. The custom hook is working very well and now I need to prevent developers in this project from using the native useNavigate hook. I configured my ESLint script as follows. And I have installed the dependency "eslint-plugin-react-hooks" The problem is, I'm getting the error "[eslint] Failed to load plugin 'no-react-hooks' declared in '.eslintrc.json': Cannot find module 'eslint-plugin-no-react-hooks'"
.eslintrc.json
{
"extends": [
"react-app",
"plugin:no-react-hooks/recommended"
],
"plugins": ["react", "no-react-hooks"],
"rules": {
"no-react-hook/use-navigate": "error"
}
}
eslint-plugin-no-react-hooks.js
module.exports = {
rules: {
'use-navigate': {
meta: {
type: 'problem',
docs: {
description: 'Prevent usage of the useNavigate hook',
category: 'Best Practices',
recommended: true,
},
},
create(context) {
return {
ImportDeclaration(node) {
if (
node.source.value === 'react-router-dom' &&
node.specifiers.some(
(specifier) => specifier.imported.name === 'useNavigate',
)
) {
context.report({
node: node,
message:
'Do not use the useNavigate hook. Instead, use "useCustomNavigate"',
});
}
},
};
},
},
},
};
How can I solve this?
I used a different approach and fixed the problem. Instead of preventing a developer from using the useNavigate hook, I set a rule to prevent a developer from importing that method through the react-router-dom module anywhere in the project as follows. (Also I added an exception using the overrides property to explicit a file to use the useNavigate hook)
eslintrc.json
{
"overrides": [
{
"files": ["src/helper.tsx"],
"rules": {
"no-restricted-imports": [
"error",
{
"paths": [
{
"name": "react-router-dom",
"importNames": [],
"message": "Importing useNavigate from react-router-dom is only allowed in this file."
}
]
}
]
}
}
],
"rules": {
"no-restricted-imports": [
"error",
{
"paths": [
{
"name": "react-router-dom",
"importNames": ["useNavigate"],
"message": "Importing useNavigate from react-router-dom is not allowed. Instead, Import useCustomNavigate from helper.tsx"
}
]
}
]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With