DEV Community

Kay Gosho
Kay Gosho

Posted on

ESlint with Class Decorator

When I create a function which returns a Decorator attached class, ESLint cause an error.

We can write such function like this:

// RequireLogin.js(error)
// @flow

import React from 'react'

@inject('userStore')
@observer
export default (ComposedComponent: *) => class RequireLogin extends React.Component<Props> {
  render() {
    if (this.props.userStore.guest) return <div>LOGIN REQUIRED</div>
    else return <ComposedComponent />
  }
}
Enter fullscreen mode Exit fullscreen mode

babel-plugin-transform-decorators-legacy can transform it as expected, but ESLint raise Syntax Error.

To pass ESLint, the code should be like this:

// RequireLogin.js(fixed)
// @flow

import React from 'react'

export default (ComposedComponent: *) => {
  @inject('userStore')
  @observer
  class RequireLogin extends React.Component<Props> {
    render() {
      if (this.props.userStore.guest) return <div>LOGIN REQUIRED</div>
      else return <ComposedComponent />
    }
  }

  return RequireLogin
}
Enter fullscreen mode Exit fullscreen mode

BTW, this HOC is simple to use:

// Home.js
// @flow

import React from 'react'
import RequireLogin from './RequireLogin'

@RequireLogin
export default class Home extends React.Component<Props> {
  render() {
    return <div>Hello</div>
  }
}
Enter fullscreen mode Exit fullscreen mode

This HOC returns referring to injected MobX's store.

  • When login user -> composed component
  • When guest user -> login component

ref: https://github.com/yannickcr/eslint-plugin-react/issues/419

Top comments (0)