Tuesday 5 November 2024

React's className vs. HTML's class: Why the Difference Matters

In React, the className attribute is used in place of the standard HTML class attribute. The reason for this is that class is a reserved keyword in JavaScript, so React uses className to avoid conflicts and ensure compatibility with JavaScript.

JSX is a syntax extension of JavaScript that looks similar to HTML but follows the rules of JavaScript. Therefore, className is used to remain compatible with JSX's syntax.

 

Example in HTML

<div class="my-class"></div>

 

Example in React Component

<div className="my-class"></div>

 

You can dynamically assign values to className using expressions.

const isActive = true;
return <div className={isActive ? "active" : "inactive"}></div>;

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment