Borislav Hadzhiev
Sat Apr 23 2022·2 min read
Photo by Jonny Clow
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.
Here is an example of how the warning is caused.
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
.
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.
// 👇️ 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
.
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.