React JSX Attributes

Working with attributes in JSX elements

🎯 What are JSX Attributes?

JSX attributes are properties you add to elements, similar to HTML attributes. However, JSX uses camelCase naming and some attributes have different names. You can set static values or use JavaScript expressions dynamically.


// JSX Attribute Example
const element = <img src="logo.png" alt="Logo" />;
                                    

Output:

Logo

Common JSX Attributes

🎨

className

CSS class names (not "class")

<div className="box"></div>
🖼️

src & alt

Image source and description

<img src="pic.jpg" alt="Photo" />
🔗

href

Link destinations

<a href="/home">Home</a>
✏️

value & type

Input field properties

<input type="text" value={val} />

🔹 className Attribute

In JSX, use className instead of class to add CSS classes to elements. This is because "class" is a reserved keyword in JavaScript, so React uses className to avoid conflicts.

// Single Class
const element = <div className="container">Content</div>;

// Multiple Classes
const box = <div className="box primary large">Box</div>;

// Dynamic Classes
const isActive = true;
const button = (
  <button className={isActive ? "active" : "inactive"}>
    Click
  </button>
);

// Template Literals for Classes
const type = "primary";
const btn = <button className={`btn btn-${type}`}>Submit</button>;

Output:

Content
Box

🔹 Style Attribute

The style attribute in JSX accepts a JavaScript object with camelCase properties instead of a CSS string. This allows you to apply inline styles dynamically using JavaScript values.

// Inline Style Object
const divStyle = {
  color: 'blue',
  backgroundColor: 'lightgray',
  padding: '10px',
  borderRadius: '5px'
};
const element = <div style={divStyle}>Styled Text</div>;

// Direct Style Object
const box = (
  <div style={{
    width: '200px',
    height: '100px',
    border: '2px solid red'
  }}>
    Box
  </div>
);

// Dynamic Styles
const color = 'green';
const text = <p style={{color: color}}>Green Text</p>;

Output:

Styled Text
Box

Green Text

🔹 Image Attributes

Image elements require src for the image source and alt for accessibility. You can also add width, height, and other attributes to control image display and behavior.

// Basic Image
const img = <img src="photo.jpg" alt="A beautiful photo" />;

// Image with Dimensions
const logo = (
  <img 
    src="logo.png" 
    alt="Company Logo"
    width="150"
    height="50"
  />
);

// Dynamic Image Source
const imagePath = "/images/banner.jpg";
const banner = <img src={imagePath} alt="Banner" />;

// Image with Style
const avatar = (
  <img 
    src="avatar.jpg" 
    alt="User Avatar"
    style={{borderRadius: '50%', width: '100px'}}
  />
);

Output:

Company Logo
Avatar

🔹 Input Attributes

Input elements use attributes like type, value, placeholder, and onChange to create interactive form fields. These attributes control input behavior and connect to React state for dynamic updates.

// Text Input
const input = (
  <input 
    type="text" 
    placeholder="Enter your name"
  />
);

// Controlled Input with Value
const [name, setName] = useState('');
const controlled = (
  <input 
    type="text"
    value={name}
    onChange={(e) => setName(e.target.value)}
  />
);

// Different Input Types
const email = <input type="email" placeholder="Email" />;
const password = <input type="password" placeholder="Password" />;
const number = <input type="number" min="0" max="100" />;
const checkbox = <input type="checkbox" checked={true} />;

Output:

🔹 Link Attributes

Anchor tags use href for destinations and target for opening behavior. In React apps, you often use React Router's Link component instead of regular anchor tags.

// Basic Link
const link = <a href="/about">About Us</a>;

// External Link
const external = (
  <a 
    href="https://example.com" 
    target="_blank"
    rel="noopener noreferrer"
  >
    Visit Example
  </a>
);

// Link with Dynamic URL
const userId = 123;
const profile = <a href={`/user/${userId}`}>View Profile</a>;

// Styled Link
const styledLink = (
  <a 
    href="/contact"
    style={{color: 'blue', textDecoration: 'none'}}
  >
    Contact
  </a>
);

🔹 Boolean Attributes

Boolean attributes like disabled, checked, and readOnly can be set using JavaScript boolean values. When true, the attribute is applied; when false, it's omitted from the element.

// Disabled Button
const isDisabled = true;
const button = <button disabled={isDisabled}>Submit</button>;

// Checked Checkbox
const isChecked = true;
const checkbox = <input type="checkbox" checked={isChecked} />;

// ReadOnly Input
const isReadOnly = true;
const input = <input type="text" readOnly={isReadOnly} value="Fixed" />;

// Multiple Boolean Attributes
const field = (
  <input 
    type="text"
    required={true}
    disabled={false}
    autoFocus={true}
  />
);

Output:



🔹 Custom Data Attributes

You can add custom data attributes to elements using the data- prefix. These are useful for storing extra information on elements that can be accessed later in JavaScript.

// Custom Data Attributes
const item = (
  <div 
    data-id="123"
    data-category="electronics"
    data-price="299"
  >
    Product Item
  </div>
);

// Dynamic Data Attributes
const productId = 456;
const product = (
  <div data-product-id={productId}>
    Product
  </div>
);

// Accessing Data Attributes
function handleClick(e) {
  const id = e.target.dataset.id;
  console.log(id); // "123"
}

🧠 Test Your Knowledge

What attribute is used instead of "class" in JSX?