Invalid DOM property `class` warning in React

avatar

Borislav Hadzhiev

Last updated: Apr 23, 2022

banner

Photo from Unsplash

Invalid DOM property class warning in React #

To fix the React.js warning "Invalid DOM property class. Did you mean className", use the className prop instead of class on your tags. The className prop is used because class is a reserved word in JavaScript.

invalid dom property class

Here is an example of how the warning is caused.

App.js
export default function App() { // ⛔️ Warning: Invalid DOM property `class`. Did you mean `className`? return ( <div> <div class="my-class">Some content</div> </div> ); }

The issue in the code sample is that we're using the class prop, however class is a reserved word in JavaScript.

To get rid of the warning, we have to use the className prop instead of class.

App.js
export default function App() { // ✅ Using className return ( <div> <div className="my-class">Some content</div> </div> ); }

The className property is not React.js specific, it's also used in browsers to programmatically set and get the value of the class attribute of the specified element.

The reason we have to use className in React is because the class keyword is a reserved word - it's used to declare an ES6 class.

App.js
// 👇️ ES6 class class Person { constructor(name, age) { this.name = name; this.age = age; } } const person = new Person('Alice', 30); console.log(person.name); // 👉️ "Alice"

Another commonly used prop name that may surprise you is - htmlFor. The htmlFor prop is in label elements instead of for.

App.js
export default function App() { return ( <div> <label htmlFor="firstName">First Name</label> <input id="firstName" type="text" /> </div> ); }

The reason we have to use htmlFor in React is because the for keyword is a reserved word - it's used in for loops.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.