28
10

More than 1 year has passed since last update.

ESLint で Component definition is missing display name が出たら、 コンポーネントに名前を付ける

Last updated at Posted at 2018-01-17

React のコンポーネントには名前を付けましょう、という名前のエラー。バグなどが発生したときに、コンポーネントを特定しやすくなるため。

よくあるのは、高階関数でコンポーネントを作ろうとして、 ESLintの Component definition is missing display name react/display-name で怒られるパターン。

対応方法

Before

下記はコンポーネントに名前が付かないため、表題のエラーが出ます。

const createTabBarIcon = (iconName: string) => ({ tintColor, focused }: Props) => {
  return (
    <Icons
      name={iconName}
      size={26}
      style={{ color: tintColor }}
    />
  )
}

After

明示的に名前を付けます。

const createTabBarIcon = (iconName: string) => function TabBarIcon({ tintColor, focused }: Props) {
  return (
    <Icons
      name={iconName}
      size={26}
      style={{ color: tintColor }}
    />
  )
}

メモなど

React Navigation の TabNavigator で、navigationOptions を共通化した関数に入れたい。
navigationOptions には関数を渡すので、Stateless Functional Component を返す関数を定義すれば良い。

この場合、関数内部で関数を定義することになるが、この定義された関数を無名関数にすると、 ESLintの Component definition is missing display name react/display-name で怒られる。

このルールは、すべてのコンポーネントに名前が無いとデバッグしづらいからと、導入されたらしい。

で、考えてみれば当然だが、関数名をつけて返せば良い。つまりアロー関数ではダメ。

コード

// @flow

import React from 'react'
import HomeScreen from './HomeScreen'
import { TabNavigator } from 'react-navigation'

type Props = {
  tintColor: string,
  focused: boolean
}

const TabBarIcon = (iconName: string) => function TabBarIconContent({ tintColor, focused }: Props): React.Component {
  return (
    <Icons
      name={iconName}
      size={26}
      style={{ color: tintColor }}
    />
  )
}

export const MainNav = TabNavigator({
  Home: { screen: HomeScreen },
  navigationOptions: {
    title: 'ホーム',
    tabBarIcon: TabBarIcon('home')
  }
})

参考

28
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
10