REACT JSX

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code directly within JavaScript. JSX makes it easier to create React components and visualize the structure of your user interface (UI).

1. What is JSX?

JSX is not a requirement for React, but it’s widely used because it simplifies coding. JSX is converted into JavaScript using tools like Babel. For example:

JSX Code:

const element = <h1>Hello, React!</h1>;

Try It Now

Compiled JavaScript:

const element = React.createElement('h1', null, 'Hello, React!');

Try It Now

2. Writing JSX

Basic JSX Syntax

JSX looks like HTML but is embedded within JavaScript. You can include elements like <div>, <h1>, and <p> inside JSX.

Example:

const element = <h1>Welcome to React!</h1>;
ReactDOM.render(element, document.getElementById('root'));

Try It Now

Embedding JavaScript in JSX

You can use curly braces {} to embed JavaScript expressions inside JSX.

Example:

const name = "React";
const element = <h1>Welcome, {name}!</h1>;
ReactDOM.render(element, document.getElementById('root'));

Try It Now

Using Functions in JSX

You can call JavaScript functions directly within JSX.

Example:

function greet(user) {
    return `Hello, ${user}!`;
}

const element = <h1>{greet("React Developer")}</h1>;
ReactDOM.render(element, document.getElementById('root'));

Try It Now

3. JSX Attributes

JSX attributes are similar to HTML attributes but use camelCase naming conventions.

Example:

const element = <img src="logo.png" alt="React Logo" />;
ReactDOM.render(element, document.getElementById('root'));

Try It Now

Special Attribute Differences

  • Use className instead of class for CSS classes.
  • Use htmlFor instead of for for labels.

Example:

const element = <label htmlFor="nameInput">Name:</label>;

Try It Now

4. JSX with Multiple Elements

In JSX, you cannot return multiple sibling elements directly. Wrap them in a parent element or use a React Fragment.

Using a Parent Element:

const element = (
    <div>
        <h1>Hello, React!</h1>
        <p>This is a paragraph.</p>
    </div>
);
ReactDOM.render(element, document.getElementById('root'));

Try It Now

Using React Fragments:

const element = (
    <>
        <h1>Hello, React!</h1>
        <p>This is a paragraph.</p>
    </>
);
ReactDOM.render(element, document.getElementById('root'));

Try It Now

5. JSX Styling

JSX supports inline styles written as objects with camelCase property names.

Example:

const style = {
    color: 'blue',
    backgroundColor: 'lightgray',
    padding: '10px',
    fontFamily: 'Arial'
};

const element = <h1 style={style}>Styled with JSX</h1>;
ReactDOM.render(element, document.getElementById('root'));

Try It Now

6. JSX Conditionals

Use JavaScript logic (e.g., ternary operators) for conditional rendering in JSX.

Example:

const isLoggedIn = true;

const element = (
    <div>
        {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
    </div>
);
ReactDOM.render(element, document.getElementById('root'));

Try It Now

7. JSX Loops

You can use the .map() function to render lists in JSX.

Example:

const items = ['Apple', 'Banana', 'Cherry'];

const element = (
    <ul>
        {items.map((item, index) => (
            <li key={index}>{item}</li>
        ))}
    </ul>
);
ReactDOM.render(element, document.getElementById('root'));

Try It Now

 

8. JSX Comments

Use {/* Comment */} for inline comments within JSX.

Example:

const element = (
    <div>
        {/* This is a comment */}
        <h1>Hello, React!</h1>
    </div>
);
ReactDOM.render(element, document.getElementById('root'));

Try It Now

9. JSX Rules

  1. Parent Element: JSX must have a single parent element.
    • Correct:
      return (
          <div>
              <h1>Hello</h1>
              <p>Welcome!</p>
          </div>
      );
      

      Try It Now

    • Incorrect:
      return (
          <h1>Hello</h1>
          <p>Welcome!</p>
      );
      

      Try It Now

  2. Close All Tags: All tags must be properly closed, including self-closing tags.
    • Correct: <img src="logo.png" alt="React Logo" />
    • Incorrect: <img src="logo.png" alt="React Logo">
  3. Use CamelCase for Attributes: Attributes must use camelCase for consistency.
    • Correct: tabIndex, onClick
    • Incorrect: tabindex, onclick
  4. Do Not Use Reserved Words: Avoid using reserved words like class and for. Use className and htmlFor instead.

 

10. JSX with Expressions

JSX can handle complex expressions, but always return valid JSX elements.

Example:

const a = 5, b = 10;
const element = <h1>The sum is: {a + b}</h1>;
ReactDOM.render(element, document.getElementById('root'));

Try It Now

11. Dangerous HTML Rendering

If you need to inject raw HTML, use the dangerouslySetInnerHTML attribute. Use with caution!

Example:

const rawHTML = { __html: '<h1 style="color: red;">Hello, Raw HTML!</h1>' };
const element = <div dangerouslySetInnerHTML={rawHTML}></div>;
ReactDOM.render(element, document.getElementById('root'));

Try It Now

12. JSX and React Components

JSX is commonly used in React components for rendering UI.

Example: Functional Component:

function Welcome() {
    return <h1>Welcome to React!</h1>;
}
ReactDOM.render(<Welcome />, document.getElementById('root'));

Try It Now

Key Points to Remember

  1. JSX simplifies the process of writing React components.
  2. JSX is not valid JavaScript—it’s transpiled to React.createElement() by Babel.
  3. Always return a single parent element in JSX.
  4. Use curly braces {} to include JavaScript logic.
  5. Use camelCase for attributes and avoid reserved words like class and for.

 

By mastering JSX, you can efficiently create React components and structure your application’s UI in a readable and declarative way.