React JSX Attributes
⚛️ React JSX Attributes
JSX allows you to add attributes to elements, just like in HTML, but there are some key differences:
Basic Example
-
classNameinstead ofclass(becauseclassis a reserved word in JS) -
JSX attributes use camelCase for most HTML attributes
Common JSX Attribute Differences
| HTML | JSX |
|---|---|
class |
className |
for |
htmlFor |
onclick |
onClick |
tabindex |
tabIndex |
maxlength |
maxLength |
readonly |
readOnly |
Dynamic Attributes Using Expressions
You can use {} to embed JavaScript values:
Or shorter with ES6 shorthand:
Event Attributes
React uses camelCase for event handlers:
Boolean Attributes
In JSX, boolean attributes are written as true/false:
-
Unlike HTML, you must provide
{true}or{false}explicitly.
Multiple Attributes
-
widthandheightvalues must be numbers (use{}).
Spread Attributes
You can pass multiple props using the spread operator:
⚡ Summary
| Feature | Example |
|---|---|
className instead of class |
<div className="container"></div> |
htmlFor instead of for |
<label htmlFor="name">Name</label> |
| Inline style | <div style={{ color: 'red', fontSize: 20 }}>Text</div> |
| Events | <button onClick={handleClick}>Click</button> |
| Boolean attributes | <input checked={true} /> |
| Spread operator | <Component {...props} /> |
JSX attributes allow you to dynamically control HTML elements in React, combine JavaScript logic, and make your components interactive.
