Skip to main content

What is JSX?

JSX (JavaScript XML) is an extension of JavaScript syntax that lets you write HTML-like code directly inside JS. It is used in React to declaratively describe what the interface (UI) should look like.


JSX example:

javascript
function App() { return <h1>Hello, world!</h1>; }

This code looks like HTML, but it actually compiles into ordinary JavaScript calls:

javascript
React.createElement("h1", null, "Hello, world!");

Why JSX is needed

Without JSX you would write React components like this:

javascript
return React.createElement("div", null, React.createElement("h1", null, "Title"), React.createElement("p", null, "Paragraph text") );

With JSX it is much simpler and clearer:

javascript
return ( <div> <h1>Title</h1> <p>Paragraph text</p> </div> );

Key features of JSX:

  1. Embedding JavaScript in markup Inside curly braces {} you can write JS expressions:
javascript
const name = "Tim"; return <h1>Hello, {name}!</h1>;
  1. JSX is not a template, it is JS syntax Everything you write ultimately turns into JavaScript functions (via Babel or SWC).
  2. One root element A JSX block must return only one parent element:
javascript
return ( <div> <h1>Title</h1> <p>Description</p> </div> ); ) // You can't return two elements at the same level without a wrapper

If you don't want to add an extra <div>, you can use a fragment:

javascript
return ( <> <h1>Title</h1> <p>Description</p> </> );
  1. Attributes - like in HTML, but in JS style:
  • class -> className

  • for -> htmlFor

  • values - in {}:

    javascript
    <img src={imageUrl} alt="Photo" /> <button disabled={isDisabled}>Button</button>
  1. JSX can contain components
javascript
function Greeting({ name }) { return <h2>Hello, {name}!</h2>; } function App() { return <Greeting name="Tim" />; }

Why JSX is convenient

The code reads like markup, but keeps the power of JavaScript You can use variables, functions and conditions directly in the UI It improves clarity and development speed


Example with a condition and a list

javascript
function TodoList({ todos }) { return ( <ul> {todos.length === 0 ? ( <p>No tasks</p> ) : ( todos.map(todo => <li key={todo.id}>{todo.text}</li>) )} </ul> ); }

JSX lets you embed logic directly into the interface structure - this is its superpower.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.