no-this-in-sfc.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // ------------------------------------------------------------------------------
  8. // Rule Definition
  9. // ------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description: 'Report "this" being used in stateless components',
  14. category: 'Possible Errors',
  15. recommended: false,
  16. url: docsUrl('no-this-in-sfc')
  17. },
  18. messages: {
  19. noThisInSFC: 'Stateless functional components should not use `this`'
  20. },
  21. schema: []
  22. },
  23. create: Components.detect((context, components, utils) => ({
  24. MemberExpression(node) {
  25. if (node.object.type === 'ThisExpression') {
  26. const component = components.get(utils.getParentStatelessComponent());
  27. if (!component || (component.node && component.node.parent && component.node.parent.type === 'Property')) {
  28. return;
  29. }
  30. context.report({
  31. node,
  32. messageId: 'noThisInSFC'
  33. });
  34. }
  35. }
  36. }))
  37. };