How to get a component’s name in React?

Sometimes, we want to get a component’s name in React.

In this article, we’ll look at how to get a component’s name in React.

How to get a component’s name in React?

To get a component’s name in React, we can use the displayName property.

For instance, we write:

import React from "react";

const Foo = () => <p>foo</p>;
Foo.displayName = "Foo";

export default function App() {
  return <Foo />;
}

to set the Foo.displayName property to the name we want.

Then we can retrieve it in the code and the React developer tools.

Conclusion

To get a component’s name in React, we can use the displayName property.