I know that setting the displayName
is sometimes required especially when you're dealing with production builds. I want to know how to set it using my functional component - is it possible/allowed?
Here's what I've got in my class component:
const MyComponent = React.createClass({ displayName: 'HeyHey', render: function() { console.log(this.displayName); } });
How do I do the same thing inside a stateless component?
When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . You may not use the ref attribute on function components because they don't have instances.
To get a component's name in React, we can use the displayName property. to set the Foo. displayName property to the name we want. Then we can retrieve it in the code and the React developer tools.
React. memo is a higher order component. If your component renders the same result given the same props, you can wrap it in a call to React. memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.
The docs for displayName
say
The
displayName
string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see Wrap the Display Name for Easy Debugging for details.
In your case, you would simply use
const MyComponent = (props) => { ... } MyComponent.displayName = 'HeyHey'
Or you can use Object.assign
const MyComponent = Object.assign ( props => { ... } , { displayName: 'HeyHey' } )
Figured it out
const MyComponent = props => { return ( <p>How you doin?</p> ) } MyComponent.displayName = "MyComponent"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With