I am working on a project which builds an ES6 React App with Webpacker. We're using ESLint to keep our scripts tidy with some pre-commit hooks, but there is one issue I haven't been able to resolve. We have a couple of React.Component
sub-classes that we use and they aren't being detected as Components
by ESLint.
Example Components:
/* AsyncComponent.jsx */
export default class AsyncComponent extends React.Component {
// Sub-classes will define _render() instead of render()
render() {
if (this.isLoaded()) {
this._render();
}
}
// "Virtual" functions which must be defined by sub-class
// isLoaded() {}
// load() {}
// _render() {}
}
/* MyComponent.jsx */
export default class MyComponent extends AsyncComponent {
// This works, but is not parsed as a Component by ESLint
// Define our "virtual" AsyncComponent functions
isLoaded() {}
load() {}
_render() {}
}
MY QUESTION: I would like to know if it is possible to configure ESLint to detect AsyncComponent
sub-classes such as MyComponent
as React.Component
sub-classes and apply the same rules that it would to other Components
.
BONUS QUESTION: This may cause an issue with the _render()
method that this particular example uses, so it would also be helpful if I could override the eslint-react rules to expect _render()
instead of render()
within AsyncComponent
sub-classes.
Relevant dependencies from package.json
:
"eslint": "^5.11.1",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-react": "^7.12.2",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-react-redux": "^3.0.1",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-redux": "^6.0.0",
"redux": "^4.0.1",
Relevant config from .eslintrc
:
"extends": [
"airbnb",
"plugin:react-redux/recommended",
"plugin:promise/recommended"
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 8,
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"impliedStrict": true,
"classes": true
}
},
"env": {
"browser": true,
"node": true,
"jquery": true,
"jest": true
},
"plugins": [
"react-redux",
"promise"
],
I'm not sure what you are trying to achieve. I think you could try return super.render()
render() {
if (this.isLoaded()) {
super.render()
}
}
But its a bad idea to extend components like this as the above says use hooks, Hocs or renderProps patterns for this kind of stuff, I know it can be confusing , especially if you come from an 'OO' background, but taking the approach you have done will be more trouble than its worth.
Thanks to @fard for his suggestion. I was trying to do this the wrong way... seems like React Higher-Order Components are the right way to do what I'm trying to achieve here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.