Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

reactjs - What is React component 'displayName' is used for?

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?

question from:https://stackoverflow.com/questions/41581130/what-is-react-component-displayname-is-used-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...