43

I have the following simple component:

import React from 'react'
import '../css.scss'

export default (props) => {
  let activeClass = props.out ? 'is-active' : ''
  return (
    <div className='hamburgerWrapper'>
      <button className={'hamburger hamburger--htla ' + activeClass}>
        <span />
      </button>
    </div>
  )
}

When I look for it in the react dev tools, I see:

enter image description here

Is this because I need to extend React component? Do I need to create this as a variable and do so?

3 Answers 3

65

This happens when you export an anonymous function as your component. If you name the function (component) and then export it, it will show up in the React Dev Tools properly.

const MyComponent = (props) => {}
export default MyComponent;
7
  • 1
    Thanks! Is it bad practice to leave it unnamed for the simple "dumb" state-less components?
    – Sequential
    Apr 17, 2017 at 20:24
  • 3
    My preference is to name, then export in different lines due to this problem. However I'd hesitate calling it a bad practice. Apr 17, 2017 at 20:27
  • This same thing affects javascript backtraces as well, for example in the Chrome dev tools. Anonymous functions will be labeled generically and this can make it hard to interpret backtraces. Sep 6, 2017 at 16:50
  • 5
    As a person who has inherited an entire app of anonymous functions that show as '<Unknown>' in react dev tools, I highly recommend you name all your components for your own sanity. See medium.com/@stevemao/… Jun 29, 2018 at 18:27
  • 2
    You can use export default function MyComponent as well
    – xyhhx
    Oct 31, 2018 at 23:07
15

I realise the original question has been correctly answered already, but I just wanted to note a very similar issue you may encounter if using React.memo() or similar function. Consider the following code:

const MyComponent = React.memo(props => <div>Hello</div>)
export default MyComponent

The component will still display as Anonymous in devtools and certain React error messages (e.g. prop-types validation).

Ensuring that the Component is defined before trying to memoise it resolves this issue, e.g:

const MyComponent = props => <div>Hello</div>
export default React.memo(MyComponent)
10

To add to Michael Jaspers answer, if you want to use a named import (instead of default export), you can do like so:

const MyComponent = props => <div />
export { MyComponent }

The component will show in React DevTools with the correct name.

Note: If you had exported the expression directly:

export const MyComponent = props => <div />

This would then show as Anonymous or Unknown in React DevTools

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.