Popular Searches
Popular Course Categories
Popular Courses

JSX Attributes

JSX Attributes

JSX in React

JSX Attributes in React

1. Introduction to JSX Attributes

JSX attributes are used to provide additional information, properties, styles, event handlers and dynamic values to JSX elements in React. They are similar to HTML attributes, but JSX follows JavaScript-based syntax rules.

Attributes allow developers to specify image sources, CSS classes, links, input values, accessibility information and other properties of elements. They can contain fixed string values or dynamic JavaScript expressions.

Example

function App() {
  return (
    <div>
      <h1 className="heading">Welcome to React</h1>
      <img src="/react-logo.png" alt="React logo" />
      <a href="https://react.dev">Learn React</a>
    </div>
  );
}
export default App;

Explanation:

  • className assigns a CSS class to the heading.
  • src specifies the image source.
  • alt provides alternative text for the image.
  • href specifies the destination of the link.

2. What Are Attributes in JSX?

Attributes are written inside the opening tag of a JSX element. They usually follow a name-value format, where the name identifies the property and the value specifies its setting.

Syntax

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

Example

function App() {
  return (
    <button type="button" className="primary-button">
      Click Me
    </button>
  );
}

In this example, type and className are JSX attributes. They define the button type and its CSS class.

In React, these values are generally referred to as props when they are passed to a React component. Built-in HTML elements also support DOM properties and event handlers through JSX.


3. Difference Between HTML Attributes and JSX Attributes

JSX resembles HTML, but some attribute names and value formats differ because JSX is written within JavaScript.

HTML Attribute JSX Attribute Purpose
class className Assigns a CSS class
for htmlFor Connects a label to a form control
onclick onClick Handles a click event
onchange onChange Handles a change event
tabindex tabIndex Controls keyboard tab order
readonly readOnly Makes a field read-only
maxlength maxLength Sets the maximum input length
style="color: blue" style={{ color: "blue" }} Applies inline styles

Important: Many JSX attributes use camelCase. However, attributes such as aria-label and data-testid retain their hyphenated names.


4. String Values in JSX Attributes

Fixed string values can be assigned to JSX attributes using quotation marks. This is useful for values that do not need to change dynamically.

Example

function App() {
  return (
    <div>
      <h1 title="Welcome Message">Hello React</h1>
      <p className="description">Learn JSX attributes.</p>
      <input type="text" placeholder="Enter your name" />
    </div>
  );
}

Explanation:

  • title="Welcome Message" sets a fixed title.
  • className="description" assigns a CSS class.
  • type="text" defines the input type.
  • placeholder="Enter your name" displays hint text inside the input.

5. Dynamic Values in JSX Attributes

Dynamic attribute values are specified using curly braces. They allow variables, calculations, object properties and other JavaScript expressions to determine attribute values.

Example

function App() {
  const imageUrl = "/images/student.png";
  const imageDescription = "Student profile";
  const imageWidth = 200;
  return (
    <img
      src={imageUrl}
      alt={imageDescription}
      width={imageWidth}
    />
  );
}

Explanation:

  • src={imageUrl} uses a JavaScript variable for the image source.
  • alt={imageDescription} provides dynamic alternative text.
  • width={imageWidth} passes a numeric value for the image width.

Important: Do not put quotation marks around a curly-brace expression. For example, use title={course}, not title="{course}", when you want the value of a variable.


6. The className Attribute

The className attribute assigns a CSS class to a JSX element. It works similarly to the HTML class attribute and is commonly used to style React components.

JSX Example

function App() {
  return (
    <div className="card">
      <h1 className="card-title">Student Profile</h1>
      <p className="card-description">Welcome to React.</p>
    </div>
  );
}

CSS Example

.card {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
}
.card-title {
  color: blue;
}
.card-description {
  font-size: 16px;
}

Using CSS classes helps keep styling separate from component markup and makes designs easier to maintain.


7. The id Attribute

The id attribute assigns a unique identifier to an HTML element. It can be used for label associations, CSS targeting, anchor navigation and other DOM-related tasks.

Example

function App() {
  return (
    <div>
      <h1 id="page-title">React Training</h1>
      <p id="course-description">
        Learn modern frontend development.
      </p>
    </div>
  );
}

Best practice: Use unique IDs when an element needs an identifier. Avoid repeating the same ID on multiple elements in the same document.


8. The href Attribute

The href attribute specifies the destination of a link. In JSX, it can contain a fixed URL or a dynamic value from a JavaScript expression.

Fixed URL Example

function App() {
  return (
    <a href="https://react.dev">
      Official React Website
    </a>
  );
}

Dynamic URL Example

function App() {
  const websiteUrl = "https://react.dev";
  return (
    <a href={websiteUrl}>
      Visit React
    </a>
  );
}

The first example uses a fixed string, while the second gets the URL from a variable.


9. The src and alt Attributes

The src attribute specifies the source of an image, while the alt attribute provides alternative text that helps users understand the image when it cannot be displayed and supports accessibility tools.

Example

function App() {
  const imageUrl = "/images/react-logo.png";
  return (
    <img
      src={imageUrl}
      alt="React logo"
      width={150}
      height={150}
    />
  );
}

Best practices:

  • Use a valid image URL or project-relative path.
  • Provide meaningful alternative text for informative images.
  • Use an empty alt="" for purely decorative images when appropriate.
  • Set image dimensions when useful for layout stability.

10. Event Handler Attributes in JSX

Event handler attributes allow React elements to respond to user interactions such as clicks, form submissions and input changes. Event handler names generally use camelCase.

Example Using onClick

function App() {
  function handleClick() {
    alert("Button clicked!");
  }
  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

Example Using an Arrow Function

function App() {
  const name = "Priya";
  return (
    <button onClick={() => alert("Hello, " + name)}>
      Greet
    </button>
  );
}

Important: Pass a function to the event attribute rather than calling it immediately during rendering. Use onClick={handleClick} or onClick={() => handleClick("Priya")}.

Common Event Handler Attributes

Attribute Purpose
onClick Handles clicks
onChange Handles input changes
onSubmit Handles form submission
onMouseEnter Handles pointer entry
onMouseLeave Handles pointer exit
onKeyDown Handles key presses

11. The style Attribute in JSX

The style attribute applies inline CSS to a JSX element. Unlike HTML, where inline styling is commonly written as a CSS string, JSX expects a JavaScript object.

Example

function App() {
  const headingStyle = {
    color: "blue",
    backgroundColor: "lightyellow",
    fontSize: "28px",
    textAlign: "center"
  };
  return (
    <h1 style={headingStyle}>
      Welcome to React
    </h1>
  );
}

Using an Inline Style Object Directly

function App() {
  return (
    <p style={{ color: "green", fontSize: "18px" }}>
      This is a styled paragraph.
    </p>
  );
}

Explanation: The outer curly braces indicate a JavaScript expression. The inner braces define the style object. CSS property names generally use camelCase, such as backgroundColor instead of background-color.

Best practice: Use CSS classes for most fixed styles and inline style objects when styles need to be set dynamically.


12. Boolean Attributes in JSX

Some JSX attributes accept Boolean values such as true and false. They are commonly used to control whether an element is disabled, checked, hidden or read-only.

Example

function App() {
  const isDisabled = true;
  return (
    <div>
      <button disabled={isDisabled}>
        Submit
      </button>
      <input type="checkbox" checked={true} readOnly />
    </div>
  );
}

Explanation:

  • disabled={isDisabled} disables the button when the variable is true.
  • checked={true} makes the checkbox checked.
  • readOnly indicates that the checkbox is not intended to be edited through user input in this example.

Note: For an interactive checkbox, use React state and an appropriate change handler instead of a permanently fixed checked value.


13. The htmlFor Attribute

In JSX, the HTML for attribute used by a label is written as htmlFor. It associates a label with a form element whose ID matches the label's value.

Example

function App() {
  return (
    <div>
      <label htmlFor="username">Username:</label>
      <input
        id="username"
        type="text"
        placeholder="Enter username"
      />
    </div>
  );
}

When the user activates the label, the browser focuses the associated input. Proper labels also improve accessibility.


14. The placeholder Attribute

The placeholder attribute provides a short hint inside an input field. It can guide users about the information they should enter.

Example

function App() {
  return (
    <form>
      <input
        type="text"
        placeholder="Enter your full name"
      />
      <input
        type="email"
        placeholder="Enter your email"
      />
    </form>
  );
}

Best practice: Use a visible label in addition to placeholder text. Placeholder text should not be the only way to identify a field.


15. The value Attribute in Form Elements

The value attribute specifies the current value of a form field. In React, passing value to an input or textarea usually makes it a controlled component, meaning its value is managed by React state.

Controlled Input Example

import { useState } from "react";
function App() {
  const [name, setName] = useState("");
  return (
    <div>
      <label htmlFor="name">Name:</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <p>Your name: {name}</p>
    </div>
  );
}
export default App;

Explanation:

  • useState("") creates state for the input value.
  • value={name} connects the input to the state.
  • onChange updates the state when the user types.
  • The paragraph displays the current value of the name.

Controlled text inputs should generally use a string value throughout their lifetime. Use defaultValue when an initial value is needed without controlling every subsequent change through state.


16. The checked Attribute in Checkbox Inputs

The checked property controls whether a checkbox is selected. In React, use state when the checkbox needs to respond to user interactions.

Example

import { useState } from "react";
function App() {
  const [isChecked, setIsChecked] = useState(false);
  return (
    <label>
      <input
        type="checkbox"
        checked={isChecked}
        onChange={(event) => setIsChecked(event.target.checked)}
      />
      Accept Terms
    </label>
  );
}
export default App;

In this example, React state controls the checkbox, and the change handler updates that state when the user selects or deselects it.


17. The target Attribute in Links

The target attribute specifies where a linked document should open. A common value is _blank, which requests opening the link in a new tab or browsing context.

Example

function App() {
  return (
    <a
      href="https://react.dev"
      target="_blank"
      rel="noopener noreferrer"
    >
      Open React Documentation
    </a>
  );
}

Explanation:

  • href specifies the destination URL.
  • target="_blank" requests a new browsing context.
  • rel="noopener noreferrer" adds protective and privacy-related behavior for the opened page.

18. The aria-* and data-* Attributes

JSX supports accessibility attributes beginning with aria- and custom data attributes beginning with data-. These attributes retain their hyphenated names in JSX rather than being converted to camelCase.

Accessibility Attribute Example

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

The aria-label provides an accessible name for the button.

Custom Data Attribute Example

function App() {
  return (
    <div data-testid="student-card" data-course="react">
      Student Information
    </div>
  );
}

Data attributes can store custom string information in the DOM. They are sometimes used for testing or integration with other tools. In React applications, component props and state are usually preferable for managing application data.


19. Passing Attributes as Props to Custom Components

When attributes are added to a custom React component, they are passed as props. The child component can use those props to determine what it renders.

Example

function Welcome(props) {
  return (
    <h1 className={props.className}>
      Hello, {props.name}!
    </h1>
  );
}
function App() {
  return (
    <div>
      <Welcome name="Rahul" className="welcome-heading" />
      <Welcome name="Priya" className="welcome-heading" />
    </div>
  );
}
export default App;

Explanation:

  • name and className are passed to the Welcome component as props.
  • props.name reads the name provided by the parent.
  • props.className applies the CSS class.
  • The same component can display different content based on its props.

20. Passing Multiple Attributes Using the Spread Operator

The JavaScript spread syntax can pass multiple properties from an object to a JSX element or custom component. This can reduce repeated attribute declarations when the object contains the appropriate props.

Example

function App() {
  const buttonProps = {
    type: "button",
    className: "primary-button",
    title: "Save your changes"
  };
  return (
    <button {...buttonProps}>
      Save
    </button>
  );
}

Explanation: The spread syntax {...buttonProps} passes the object's properties as JSX props.

Best practice: Spread only properties that are appropriate for the target element or component. Avoid passing unnecessary or unexpected props to DOM elements.


21. Common JSX Attribute Errors and Solutions

Error Reason Solution
Using class HTML attribute syntax was used in JSX. Use className.
Using for on a label The HTML attribute name was used. Use htmlFor.
Putting a variable in quotes The variable is treated as a literal string. Use curly braces, such as src={imageUrl}.
Using an invalid style string JSX expects a style object. Use style={{ color: "blue" }}.
Calling an event handler immediately The function runs during rendering. Pass a function reference or arrow function.
Missing image alt text Image accessibility may be reduced. Add meaningful alt text when appropriate.
Controlled input does not update The value is fixed or the state is not updated. Use state and an appropriate onChange handler.
Duplicate IDs Multiple elements share the same identifier. Use unique IDs.
Unnecessary props on DOM elements A custom or unsupported property is passed unintentionally. Pass only relevant DOM attributes or consume custom props in the component.

22. Practical Example: Student Registration Form

This example combines common JSX attributes, labels, controlled inputs, event handlers and dynamic content in a simple registration form.

import { useState } from "react";
function StudentRegistration() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [course, setCourse] = useState("React JS");
  function handleSubmit(event) {
    event.preventDefault();
    alert("Registration submitted for " + name);
  }
  return (
    <form className="registration-form" onSubmit={handleSubmit}>
      <h1>Student Registration</h1>
      <div>
        <label htmlFor="student-name">Name:</label>
        <input
          id="student-name"
          type="text"
          placeholder="Enter your name"
          value={name}
          onChange={(event) => setName(event.target.value)}
          required
        />
      </div>
      <div>
        <label htmlFor="student-email">Email:</label>
        <input
          id="student-email"
          type="email"
          placeholder="Enter your email"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          required
        />
      </div>
      <div>
        <label htmlFor="student-course">Course:</label>
        <select
          id="student-course"
          value={course}
          onChange={(event) => setCourse(event.target.value)}
        >
          <option value="React JS">React JS</option>
          <option value="JavaScript">JavaScript</option>
          <option value="HTML and CSS">HTML and CSS</option>
        </select>
      </div>
      <button type="submit">Register</button>
      <p>Selected course: {course}</p>
    </form>
  );
}
export default StudentRegistration;

Attributes Used in This Example

  • className styles the form.
  • onSubmit handles form submission.
  • htmlFor associates each label with its field.
  • id identifies each form control.
  • type specifies the input type.
  • placeholder provides a hint.
  • value connects the fields to React state.
  • onChange updates state as the user enters information.
  • required makes the field required by browser validation.

23. Best Practices for Using JSX Attributes

  • Use correct JSX property names, such as className and htmlFor.
  • Use quotation marks for fixed strings and curly braces for JavaScript expressions.
  • Use meaningful alternative text for informative images.
  • Associate form labels with controls using htmlFor and id.
  • Use React state for interactive controlled form fields.
  • Pass function references to event handlers.
  • Use CSS classes for most fixed styling and inline styles for suitable dynamic cases.
  • Keep aria-* and data-* attribute names in their proper hyphenated form.
  • Use the correct attributes for the element being rendered.
  • Avoid passing unnecessary props to built-in DOM elements.
  • Keep component props clear, meaningful and easy to understand.

24. Frequently Asked Interview Questions

Q1. What are JSX attributes?

JSX attributes provide values, properties, styles, event handlers and other information to JSX elements or React components.

Q2. What is the difference between HTML attributes and JSX attributes?

JSX follows JavaScript-oriented naming conventions for many properties. For example, it uses className instead of class and htmlFor instead of for.

Q3. How do you pass a dynamic value to a JSX attribute?

Use curly braces, such as src={imageUrl} or disabled={isDisabled}.

Q4. What is the purpose of className?

The className attribute assigns CSS classes to JSX elements.

Q5. What is the purpose of htmlFor?

The htmlFor attribute associates a label with a form control by matching the control's ID.

Q6. How do you apply inline CSS in JSX?

Use a JavaScript object with the style attribute, for example style={{ color: "blue" }}.

Q7. How are event handlers specified in JSX?

Event handlers use names such as onClick and receive function references or suitable arrow functions.

Q8. What are controlled inputs?

Controlled inputs are form elements whose current values are managed by React, usually through state and change handlers.

Q9. What are aria-* attributes?

They provide accessibility information to assistive technologies. Their hyphenated names are retained in JSX.

Q10. Can we pass attributes to custom React components?

Yes. Values written on a custom component are passed as props, which the component can use to determine its output.


25. Practice Exercises

  1. Create a heading with a className attribute.
  2. Create a link using a fixed href value.
  3. Display an image using dynamic src and alt values.
  4. Create a button with an onClick event handler.
  5. Build a text input using placeholder, value and onChange.
  6. Associate a label with an input using htmlFor and id.
  7. Apply inline styling using a JavaScript object.
  8. Create a checkbox controlled by React state.
  9. Build a reusable component that accepts a name and a CSS class as props.
  10. Create a registration form that uses common JSX attributes correctly.

26. Quick Revision Checklist

  • Understand the meaning and purpose of JSX attributes.
  • Know the difference between HTML and JSX attribute names.
  • Use className and htmlFor correctly.
  • Use quotation marks for fixed string values.
  • Use curly braces for dynamic JavaScript values.
  • Understand the src, alt, href and id attributes.
  • Know how to use event handlers such as onClick and onChange.
  • Apply inline styles with JavaScript objects.
  • Understand Boolean attributes and controlled form fields.
  • Know how to pass props to custom React components.
  • Use accessible attributes and follow JSX best practices.

27. Conclusion

JSX attributes are an essential part of React development because they allow developers to configure elements, apply styles, handle events, display dynamic content and build interactive forms. Understanding fixed strings, dynamic expressions, event handlers, Boolean attributes and component props helps developers write cleaner, more accessible and maintainable React applications.

28. Learn React JS with JustAcademy

Explore the React JS Training Course to improve your knowledge of JSX, components, attributes and modern frontend development.

JustAcademy React JS Training Course

Register for a demo session to learn more about the course and its training approach.

Register for React JS Course Demo

29. Official React Documentation

Refer to the official React documentation for more details about JSX syntax and supported DOM properties.

React Official Documentation: Writing Markup with JSX

React Official Documentation: Common DOM Component Props

Previous Next
whatsapp