Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is React component 'displayName' is used for?

Tags:

reactjs

eslint

I know that is it considered a good practice to name react component by adding a displayName property, but not sure I know why. In react docs, it say:

The displayName string is used in debugging messages. JSX sets this value automatically; see JSX in Depth.

Why is is so important? what will happen if I won't add it? (so far I didn't have it and had no issues debugging)

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

like image 545
Kuf Avatar asked Jan 11 '17 01:01

Kuf


People also ask

Why React key attribute is needed?

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used to React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists.

How do I set a display name in React?

const MyComponent = React. createClass({ displayName: 'HeyHey', render: function() { console. log(this. displayName); } });

What are refs in React used for?

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.


2 Answers

I have always set displayName to the same name as the variable I am assigning it to. This is would only been used in development builds as it is removed through dead-code elimination on production builds and should not be relied on within your application.

As for where it is used, that is mainly within react error messaging. This is why it is mentioned to be valuable for debugging. If no name can be derived the error messages default to say Component which is extremely difficult to debug, when you have any more than 1 component in your project.

Here are a few error messages that reference displayName in the react source:

Invalid Return

Inline style error

like image 142
kwelch Avatar answered Oct 05 '22 23:10

kwelch


this article helped me:

How do I get string name of React Native component class?

    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       }     } 
like image 27
Edward Koetsjarjan Avatar answered Oct 05 '22 23:10

Edward Koetsjarjan