DEV Community

Kay Gosho
Kay Gosho

Posted on

2 2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay