no-this-in-sfc.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * @fileoverview Report "this" being used in stateless functional components.
  3. */
  4. 'use strict';
  5. const Components = require('../util/Components');
  6. const docsUrl = require('../util/docsUrl');
  7. const report = require('../util/report');
  8. // ------------------------------------------------------------------------------
  9. // Rule Definition
  10. // ------------------------------------------------------------------------------
  11. const messages = {
  12. noThisInSFC: 'Stateless functional components should not use `this`',
  13. };
  14. /** @type {import('eslint').Rule.RuleModule} */
  15. module.exports = {
  16. meta: {
  17. docs: {
  18. description: 'Disallow `this` from being used in stateless functional components',
  19. category: 'Possible Errors',
  20. recommended: false,
  21. url: docsUrl('no-this-in-sfc'),
  22. },
  23. messages,
  24. schema: [],
  25. },
  26. create: Components.detect((context, components, utils) => ({
  27. MemberExpression(node) {
  28. if (node.object.type === 'ThisExpression') {
  29. const component = components.get(utils.getParentStatelessComponent(node));
  30. if (!component || (component.node && component.node.parent && component.node.parent.type === 'Property')) {
  31. return;
  32. }
  33. report(context, messages.noThisInSFC, 'noThisInSFC', {
  34. node,
  35. });
  36. }
  37. },
  38. })),
  39. };