Clean β’ Professional
In React, JSX attributes are used to pass data and behavior to elements, similar to HTML attributes, but with some important differences. Understanding JSX attributes is essential for building dynamic, interactive, and accessible components.
JSX allows you to set properties on elements using HTML-like attributes:
const element = <input type="text" placeholder="Enter your name" />;
| HTML Attribute | JSX Attribute | Notes |
|---|---|---|
class | className | Avoids conflict with JavaScript class keyword |
for | htmlFor | Used with <label> elements |
onclick | onClick | Event handlers use camelCase in JSX |
tabindex | tabIndex | Uses camelCase |
Example:
<label htmlFor="username">Username:</label>
<input id="username" className="input-field" />
JSX allows embedding JavaScript expressions inside attributes using {}:
const imageUrl = "<https://example.com/logo.png>";
const width = 200;
const element = <img src={imageUrl} width={width} alt="Logo" />;
React uses camelCase event attributes for user interactions:
onClick, onChange, onSubmit, onMouseOver.function handleClick() {
alert("Button clicked!");
}
const element = <button onClick={handleClick}>Click Me</button>;
Some attributes are boolean and donβt require a value:
<input type="checkbox" checked={true} />
<input type="text" disabled />
data-* syntax:<div data-id="123">Item</div>
className β CSS Classes in JSXclass is used for styling.className replaces class to avoid conflicts with JavaScript keywords:const element = <div className="container">Hello, React!</div>;
Apply multiple classes using a space-separated string:
<div className="container main-content">Content</div>
htmlFor β Label Association<label> uses for to link to inputs.htmlFor instead:<label htmlFor="username">Username:</label>
<input id="username" type="text" />
const buttonStyle = {
backgroundColor: 'blue',
color: 'white',
padding: '10px 20px',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
};
function StyledButton() {
return <button style={buttonStyle}>Click Me</button>;
}
Inline styles are useful for dynamic or conditional styling:
const isActive = true;
const style = { color: isActive ? 'green' : 'gray' };
<p style={style}>Status</p>Β