What is the React 'displayName' component used for?

I know that he thought it was good practice to name the component of the reaction by adding the displayName property, but I'm not sure I know why. The response docs say:

The displayName string is used to debug messages. JSX automatically sets this value; see JSX in depth.

Why is it so important? What happens if I do not add it? (so far I haven’t had it and there have been no debugging problems)

Are there any recommendations / recommendations on how to name the components?

+12
source share
2 answers

I always set displayName to the same name as the variable to which I assign it. This will only be used in development builds, as it is removed by eliminating dead code in production builds and should not rely on your application.

As for where it is used, this mainly happens when exchanging error messages. This is why it is referred to as useful for debugging. If no name can be obtained, the default error messages say Component , which are extremely difficult to debug if your project has more than one component.

Here are some error messages that reference displayName in the response source:

Invalid return

Inline style error

+16
source

this article helped me:

How to get the string name of a class of a React Native component?

  class CardGroup extends Component { render() { return ( <div>{this.props.children}</div> ) } } CardGroup.propTypes = { children: function (props, propName, componentName) { const prop = props[propName] let error = null React.Children.forEach(prop, function (child) { if (child.type !== Card) { error = new Error(''' + componentName + '' children should be of type 'Card'.'); } }) return error } } 
0
source

Source: https://habr.com/ru/post/1262615/


All Articles