JSX Attributes
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.
Basic JSX Attributes
JSX allows you to set properties on elements using HTML-like attributes:
const element = <input type="text" placeholder="Enter your name" />;
Differences from HTML Attributes
| 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" />
Passing Dynamic Values to Attributes
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" />;
Event Handling with Attributes
React uses camelCase event attributes for user interactions:
- Common events:
onClick,onChange,onSubmit,onMouseOver.
function handleClick() {
alert("Button clicked!");
}
const element = <button onClick={handleClick}>Click Me</button>;
Boolean Attributes
Some attributes are boolean and don’t require a value:
<input type="checkbox" checked={true} />
<input type="text" disabled />
Custom Attributes and Data Attributes
- You can define custom attributes using
data-*syntax:
<div data-id="123">Item</div>
className – CSS Classes in JSX
- In HTML,
classis used for styling. - In JSX,
classNamereplacesclassto 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
- In HTML,
<label>usesforto link to inputs. - In JSX, use
htmlForinstead:
<label htmlFor="username">Username:</label>
<input id="username" type="text" />
Inline Styles in JSX
- Use JavaScript objects for inline CSS styles.
- CSS properties use camelCase, and values are usually strings or numbers:
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>
