React JSX


What is JSX in React?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. It is used in React to describe the structure of the user interface in a way that is similar to HTML. JSX gets compiled to JavaScript, typically using a tool like Babel, and becomes React's React.createElement() calls under the hood.


What is the advantage of using JSX?

JSX provides the following advantages:

  • Readable and declarative: JSX makes it easier to visualize the UI structure, allowing you to write code that looks similar to HTML or XML.
  • Component-based structure: JSX allows you to easily embed and work with React components.
  • Familiar syntax: Developers familiar with HTML feel comfortable working with JSX.
  • Powerful tooling: Tools like Babel can compile JSX into efficient JavaScript code.

How is JSX transformed into JavaScript?

JSX is not valid JavaScript, so it needs to be transformed into JavaScript code that browsers can understand. This transformation is typically done by a tool like Babel, which converts JSX into React.createElement() calls.

Example of JSX and its transformation:


// JSX
const element = <h1>Hello, world!</h1>;

// Compiled JavaScript
const element = React.createElement('h1', null, 'Hello, world!');

In the compiled JavaScript, React.createElement() is used to create the element h1 with the text "Hello, world!".


Can you write JSX without a parent element?

In JSX, you cannot return multiple adjacent elements without wrapping them in a parent element. However, you can use a React feature called React.Fragment (or the shorthand syntax <> and </>) to group elements without adding an extra DOM node.

Example of using a fragment:


// Without React.Fragment
function App() {
    return (
        <div>
            <h1>Heading</h1>
            <p>This is a paragraph.</p>
        </div>
    );
}

// With React.Fragment
function App() {
    return (
        <>
            <h1>Heading</h1>
            <p>This is a paragraph.</p>
        </>
    );
}

How do you embed JavaScript expressions inside JSX?

You can embed JavaScript expressions in JSX by enclosing them within curly braces {}. Any valid JavaScript expression can be used inside JSX, including variables, function calls, and expressions like conditionals or loops.

Example of embedding JavaScript expressions:

const name = "John";

function Greeting() {
    return <h1>Hello, {name}!</h1>;
}

function getGreeting() {
    return <h1>Good Morning!</h1>;
}

const element = <div>{getGreeting()}</div>;

What are the rules of JSX syntax?

JSX follows a few syntax rules:

  • Elements must be closed: All JSX elements must be closed, either with a closing tag (e.g., <div></div>) or self-closing (e.g., <img />).
  • Use camelCase for attributes: JSX attributes follow camelCase naming (e.g., className instead of class).
  • JavaScript expressions inside curly braces: Any JavaScript logic must be wrapped in curly braces {} within JSX.
  • Only one top-level element: JSX must return a single root element or use fragments to wrap multiple elements.

How do you apply CSS classes in JSX?

In JSX, you use the className attribute instead of the standard HTML class attribute. This is because class is a reserved keyword in JavaScript.

Example of applying CSS classes:

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

In this example, the CSS class container is applied to the div element.


How do you add inline styles in JSX?

To apply inline styles in JSX, you use the style attribute and pass an object where the keys are camelCased CSS properties and the values are strings or variables.

Example of inline styles in JSX:

const element = <div style={{ color: 'red', backgroundColor: 'yellow' }}>
    This is styled text.
</div>;

In this example, the color and backgroundColor properties are applied to the div element using an inline style object.


Can JSX be used with conditional rendering?

Yes, JSX can be used with conditional rendering. You can use JavaScript conditionals such as if, ternary operators, or && (logical AND) within JSX to conditionally render elements.

Example of conditional rendering:

const isLoggedIn = true;

function Welcome() {
    return (
        <div>
            {isLoggedIn ? <h1>Welcome, User!</h1> : <h1>Please log in.</h1>}
        </div>
    );
}

In this example, a ternary operator is used to conditionally render either the welcome message or the login prompt based on the value of isLoggedIn.


What is the purpose of React.createElement() in JSX?

React.createElement() is the function that JSX is ultimately compiled into. It creates a React element from the specified component or HTML tag. Although JSX is commonly used to define components, React.createElement() is the core function behind the scenes.

Example of JSX being compiled into React.createElement():

// JSX
const element = <h1>Hello, world!</h1>;

// Compiled JavaScript
const element = React.createElement('h1', null, 'Hello, world!');

In this example, JSX is converted to React.createElement() calls that generate React elements.


Can JSX be used without React?

JSX is specifically designed to be used with React, as it is compiled into React.createElement() calls. However, you can configure tools like Babel to compile JSX into function calls for other libraries. Still, the vast majority of JSX use cases involve React.

Example of using JSX with a different library (hypothetical):

// Hypothetical function
function createMyElement(tag, props, ...children) {
    return { tag, props, children };
}

// JSX compiled to a custom function call
const element = createMyElement('div', null, 'Hello, World!');
Ads