Popular Searches
Popular Course Categories
Popular Courses

JSX Attributes

JSX Attributes

JSX in React

JSX Attributes in React JS – Detailed Notes

JSX Attributes are used to provide additional information to HTML-like elements in JSX. They allow developers to set properties such as an element's ID, class, style, image source, alternative text, event handlers, and custom component props. JSX attributes look similar to HTML attributes, but some names and rules differ because JSX is written within JavaScript.

These notes explain JSX attributes in React JS with syntax, examples, rules, practical applications, common mistakes, interview questions, and revision points.


1. What Are JSX Attributes?

JSX attributes are written inside the opening tag of a JSX element. They configure how an element behaves, appears, or receives data.

Example:

const element = <input type="text" placeholder="Enter your name" />;

In this example:

  • type="text" defines the type of input.
  • placeholder="Enter your name" displays hint text inside the input.

JSX attributes can use static values, JavaScript expressions, Boolean values, objects, and function references, depending on the attribute.


2. Basic Syntax of JSX Attributes

The basic syntax places attributes inside the opening JSX tag.

<element attributeName="value">Content</element>

Example:

function App() {
  return (
    <div id="container" className="main-container">
      <h1>Welcome to React JS</h1>
    </div>
  );
}
export default App;

Here, id identifies the element, while className assigns a CSS class to it.


3. JSX Attributes vs HTML Attributes

JSX is similar to HTML, but JSX attributes follow JavaScript naming conventions and React-specific rules.

HTML Attribute JSX Attribute Purpose
class className Assigns a CSS class.
for htmlFor Connects a label to a form control.
tabindex tabIndex Controls keyboard focus order.
onclick onClick Handles a click event using a function.
readonly readOnly Makes a form control read-only.
maxlength maxLength Sets the maximum text length.

Important: Use the correct JSX attribute name and capitalization. React event props such as onClick use camelCase.


4. Using className Instead of class

In JSX, use className to assign a CSS class rather than the HTML attribute class.

Example:

function App() {
  return (
    <div className="card">
      <h2 className="card-title">React JS</h2>
      <p className="card-description">Learn component-based development.</p>
    </div>
  );
}

Corresponding CSS:

.card {
  padding: 20px;
  border: 1px solid #ccc;
}
.card-title {
  font-size: 24px;
}
.card-description {
  color: #555;
}

Why use className? JSX uses JavaScript-compatible property names. React translates the JSX into the appropriate DOM operations.


5. String Values in JSX Attributes

Static text values can be provided using single or double quotation marks.

function App() {
  return (
    <div>
      <input type="text" placeholder="Enter your name" />
      <img src="logo.png" alt="Company logo" />
      <a href="https://example.com">Visit Website</a>
    </div>
  );
}

In this example, type, placeholder, src, alt, and href receive string values.


6. Using JavaScript Expressions in JSX Attributes

Use curly braces { } to provide a JavaScript expression as an attribute value. This is useful when values come from variables, calculations, function calls, or component state.

Example:

function App() {
  const userName = "Rahul";
  const imageUrl = "/images/profile.png";
  const imageDescription = "Rahul's profile";

  return (
    <div>
      <h1>Welcome, {userName}!</h1>
      <img src={imageUrl} alt={imageDescription} />
    </div>
  );
}

Here, src={imageUrl} passes the value stored in the imageUrl variable to the image's source attribute.

Remember: Use quotation marks for literal strings and curly braces for JavaScript expressions.

<h1 title="Welcome">Hello</h1>
<h1 title={pageTitle}>Hello</h1>

7. Dynamic JSX Attributes

Dynamic attributes allow values to change based on variables, props, or state. They are useful for user profiles, product listings, conditional styling, and interactive interfaces.

Example:

function UserProfile() {
  const name = "Priya";
  const isVerified = true;

  return (
    <div>
      <h2 title={`Profile of ${name}`}>{name}</h2>
      <button disabled={!isVerified}>
        {isVerified ? "Verified" : "Verification Required"}
      </button>
    </div>
  );
}

The title attribute is generated from a template literal. The disabled attribute depends on the value of isVerified.


8. Boolean Attributes in JSX

Boolean attributes represent settings that can be enabled or disabled. Common examples include disabled, checked, required, readOnly, and multiple.

Example:

function App() {
  const isDisabled = true;
  const isRequired = false;

  return (
    <form>
      <input type="text" disabled={isDisabled} required={isRequired} />
      <button disabled={isDisabled}>Submit</button>
    </form>
  );
}

For a Boolean attribute, you can also use a shorthand when you want its value to be true.

<button disabled>Please Wait</button>
<input type="checkbox" checked />

To set the attribute to false explicitly, use an expression such as disabled={false}. For checkboxes and other controlled form elements, the value should be managed consistently with React state and the relevant change handler.


9. Event Handler Attributes

React event handler props use camelCase names and usually receive a function reference inside curly braces.

Example:

function App() {
  function handleClick() {
    alert("Button clicked!");
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

Here, onClick receives the handleClick function. React calls the function when the user clicks the button.

Incorrect:

<button onClick="handleClick()">Click Me</button>

Correct:

<button onClick={handleClick}>Click Me</button>

You can also use an arrow function for a short handler or when passing an argument:

<button onClick={() => alert("Hello!")}>Say Hello</button>

Do not call a handler directly during rendering when you intend it to run only after an event. For example, use onClick={handleClick}, not onClick={handleClick()}.


10. The htmlFor Attribute

Use htmlFor in JSX to associate a label with a form control. It corresponds to the HTML for attribute.

function App() {
  return (
    <div>
      <label htmlFor="email">Email Address</label>
      <input id="email" type="email" placeholder="Enter email" />
    </div>
  );
}

When a user clicks the label, the associated input can receive focus. Proper label association also improves accessibility.


11. The style Attribute in JSX

Unlike a plain HTML style string, React's JSX style attribute normally accepts a JavaScript object. CSS property names generally use camelCase, and values that represent lengths usually use pixel units when provided as numbers, except for unitless CSS properties.

function App() {
  const headingStyle = {
    color: "blue",
    backgroundColor: "lightgray",
    fontSize: "28px",
    padding: "12px"
  };

  return (
    <h1 style={headingStyle}>
      Welcome to React JS
    </h1>
  );
}

You can also write the style object inline:

<p style={{ color: "green", fontSize: "18px" }}>
  This is a styled paragraph.
</p>

The outer braces indicate a JavaScript expression, and the inner braces create the JavaScript object.

Important: Prefer CSS classes for reusable styling. Inline styles are useful for simple dynamic styles.


12. Passing Props as Attributes to React Components

JSX attributes are also used to pass data to custom React components. These values are called props.

Example:

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Aarav" />
      <Welcome name="Priya" />
    </div>
  );
}

export default App;

In this example, name="Aarav" and name="Priya" are component attributes. React passes their values to the Welcome component through props.

You can pass non-string values with curly braces:

<Welcome name={userName} age={25} isActive={true} />

Inside the component, these values are accessed through the props object or by destructuring:

function Welcome({ name, age, isActive }) {
  return (
    <p>
      {name} is {age} years old. Active: {isActive ? "Yes" : "No"}
    </p>
  );
}

13. The Spread Syntax in JSX Attributes

The spread syntax (...) can pass multiple properties from an object to a JSX element or component. It is helpful when a set of attributes is already stored in an object.

function App() {
  const inputProps = {
    type: "text",
    placeholder: "Enter your name",
    maxLength: 30
  };

  return <input {...inputProps} />;
}

This is similar to writing:

<input type="text" placeholder="Enter your name" maxLength={30} />

Spread syntax can also pass props to custom components:

const user = {
  name: "Neha",
  age: 22
};

<UserProfile {...user} />

Best practice: Only spread objects that contain appropriate and trusted props. Avoid passing unrelated or unwanted properties to DOM elements.


14. Conditional JSX Attributes

Sometimes an attribute should change depending on a condition. You can use ternary expressions or logical expressions to calculate its value.

Example using a ternary expression:

function App() {
  const isLoggedIn = false;

  return (
    <button disabled={isLoggedIn ? false : true}>
      Continue
    </button>
  );
}

A simpler equivalent is:

<button disabled={!isLoggedIn}>Continue</button>

For conditional class names, you can use a template literal:

function Status() {
  const isOnline = true;

  return (
    <p className={`status ${isOnline ? "online" : "offline"}`}>
      {isOnline ? "Online" : "Offline"}
    </p>
  );
}

For larger conditional class combinations, a helper function or class-name utility may improve readability.


15. Custom Data Attributes

HTML supports custom data attributes that begin with data-. These can store extra information on a DOM element.

function App() {
  return (
    <button data-user-id="101" data-role="admin">
      View User
    </button>
  );
}

You can use JavaScript expressions to set their values:

const productId = 205;
<div data-product-id={productId}>Product Details</div>

Custom data attributes can be read from the DOM through element.dataset. Do not store secrets or sensitive information in them because DOM attributes can be inspected by users.


16. Accessibility Attributes in JSX

Accessibility attributes help assistive technologies understand and describe elements. Examples include aria-label, aria-hidden, aria-expanded, and role.

function App() {
  return (
    <button aria-label="Close dialog" onClick={() => console.log("Closed")}>
      X
    </button>
  );
}

Here, aria-label provides an accessible name for the button. Use semantic HTML elements whenever possible, and apply ARIA attributes when they are needed to communicate meaning or state.

Another example:

<div role="status" aria-live="polite">
  Your form has been submitted.
</div>

17. Common Mistakes in JSX Attributes

Mistake Correct Approach Reason
class="box" className="box" Use className for CSS classes in JSX.
for="email" htmlFor="email" JSX uses htmlFor for labels.
onClick="save()" onClick={save} Event handlers should receive a function.
title={Hello} title="Hello" Use quotes for a literal string.
src="imageUrl" src={imageUrl} Use braces when referencing a variable.
style="color: red" style={{ color: "red" }} JSX style expects an object.
disabled="false" disabled={false} A string is not the same as Boolean false.
onclick={handleClick} onClick={handleClick} React event prop names use camelCase.

18. Practical Example: Product Card Using JSX Attributes

This example demonstrates string attributes, dynamic values, CSS classes, inline styles, and event handlers together.

function ProductCard() {
  const product = {
    name: "Wireless Headphones",
    price: 1999,
    image: "/images/headphones.png",
    available: true
  };

  function handleBuy() {
    alert(`You selected ${product.name}`);
  }

  return (
    <div className="product-card">
      <img
        src={product.image}
        alt={product.name}
        width={200}
      />
      <h2 title={product.name}>{product.name}</h2>
      <p>Price: ₹{product.price}</p>
      <p className={product.available ? "in-stock" : "out-of-stock"}>
        {product.available ? "In Stock" : "Out of Stock"}
      </p>
      <button onClick={handleBuy} disabled={!product.available}>
        Buy Now
      </button>
    </div>
  );
}

export default ProductCard;

What this example teaches:

  • className applies CSS classes.
  • src and alt configure the image.
  • title receives a dynamic string.
  • onClick handles the button click.
  • disabled depends on product availability.
  • className changes according to a condition.

19. Best Practices for JSX Attributes

  • Use className instead of class for CSS classes.
  • Use htmlFor to associate labels with form controls.
  • Use quotation marks for static string values.
  • Use curly braces for JavaScript expressions and variables.
  • Use camelCase for React event handlers, such as onClick and onChange.
  • Pass function references to event handlers instead of calling them during rendering.
  • Use a JavaScript object for inline styles.
  • Keep custom component props clear and meaningful.
  • Use accessible names and labels for interactive elements.
  • Do not pass unnecessary or sensitive information to DOM attributes.
  • Use controlled form elements consistently when their values are managed by React state.
  • Prefer readable, reusable components over complicated inline expressions.

20. Interview Questions and Answers on JSX Attributes

Q1. What are JSX attributes?

JSX attributes configure elements and components by providing values such as IDs, CSS classes, image sources, event handlers, and component props.

Q2. Why do we use className instead of class?

JSX uses JavaScript-compatible property names. Therefore, className is used to assign CSS classes to elements.

Q3. How do you pass a variable to a JSX attribute?

Use curly braces around the variable, for example, Profile.

Q4. How are event handlers written in JSX?

Event handlers use camelCase names and receive function references, for example, .

Q5. What is the difference between a string attribute and an expression attribute?

A string attribute uses quotation marks, such as title="Welcome". An expression attribute uses curly braces, such as title={pageTitle}.

Q6. How do you apply inline styles in JSX?

Pass a JavaScript object to the style attribute, for example, style={{ color: "red", fontSize: "20px" }}.

Q7. What are props in React?

Props are values passed from a parent component to a child component. They can be supplied through JSX attributes.

Q8. What is the spread syntax in JSX?

The spread syntax, ..., passes properties from an object to an element or component, for example, .

Q9. How can you conditionally disable a button?

Use a Boolean expression, such as .

Q10. What is htmlFor?

htmlFor is the JSX attribute used to associate a label with a form element's ID.


21. Quick Revision Checklist

  • Understand the meaning and purpose of JSX attributes.
  • Know the difference between JSX and HTML attribute names.
  • Use className and htmlFor correctly.
  • Know when to use quotation marks and curly braces.
  • Understand Boolean and dynamic attributes.
  • Write event handlers using camelCase props.
  • Apply inline styles using JavaScript objects.
  • Pass data to components through props.
  • Use spread syntax carefully.
  • Understand accessibility and custom data attributes.
  • Practice building a product card or profile component.

22. Conclusion

JSX attributes are an essential part of React JS because they let developers configure HTML elements and pass data to custom components. Understanding static strings, dynamic expressions, Boolean values, event handlers, styles, props, and accessibility attributes helps you write clean and interactive React applications.

Continue learning React JS by studying JSX expressions, components, props, state, event handling, conditional rendering, and lists.

Useful React JS Training Links

whatsapp