The displayName property in React is used to set a custom name for a component, mainly for debugging and developer tools.
1. Why Use displayName?
By default, React components are named based on their function name or class name. However, in some cases:
- Components are anonymous functions, making debugging harder.
- Higher-Order Components (HOCs) wrap components, hiding their original name.
Setting displayName helps in React DevTools and error messages.
2. Using displayName in Functional Components
If a component is defined as an anonymous function, React assigns it a generic name.
const MyComponent = () => <h2>Hello, React!</h2>; MyComponent.displayName = "CustomComponent"; export default MyComponent;
3. Using displayName in Class Components
For class components, displayName is explicitly set as a static property.
import React from "react";
class MyComponent extends React.Component {
static displayName = "CustomComponent";
render() {
return <h2>Hello, React!</h2>;
}
}
export default MyComponent;
This helps when a class component gets wrapped inside an HOC.
4. Using displayName in Higher-Order Components (HOCs)
When a component is wrapped in an HOC, its original name gets hidden.
const withLogger = (WrappedComponent) => {
const NewComponent = (props) => <WrappedComponent {...props} />;
NewComponent.displayName = `WithLogger(${WrappedComponent.displayName || WrappedComponent.name})`;
return NewComponent;
};
// Usage
const MyComponent = () => <h2>Hello, React!</h2>;
const EnhancedComponent = withLogger(MyComponent);
console.log(EnhancedComponent.displayName); // Output: "WithLogger(MyComponent)"
This ensures HOCs preserve meaningful names in DevTools.
5. When to Use displayName?
Debugging: Helps React DevTools show clear component names.
HOCs & Wrappers: Ensures wrapped components retain meaningful names.
Anonymous Components: Gives better identification in error logs.
6. Conclusion
displayNameis used for debugging and naming components in React DevTools.- Useful for HOCs, anonymous components, and better error messages.
- Not required in most cases, but improves developer experience.
