Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

JSX

JSX is a way to write markup right inside JavaScript code. It looks like HTML, but during the build Vite turns it into ordinary React function calls. Thanks to JSX, a component's markup and logic live in one file. Files with JSX get the .jsx extension.

Markup in a component

Open src/App.jsx. Multi-line markup is wrapped in parentheses:

// src/App.jsx
export default function App() {
  return (
    <div>
      <h1>My tasks</h1>
      <p>Things to do today.</p>
    </div>
  );
}

The page shows a heading and a paragraph below it.

Expressions in curly braces

Inside curly braces you can write any JavaScript expression: a variable, a calculation, a function call.

// src/App.jsx
export default function App() {
  const name = 'Anna';
  const total = 3;
 
  return (
    <div>
      <h1>Tasks of {name}</h1>
      <p>Left to do: {total * 2}</p>
    </div>
  );
}

The page shows "Tasks of Anna" and "Left to do: 6". Statements like if or for are not allowed in the braces — only expressions that produce a value.

Attributes

String values go in quotes, values from JavaScript go in curly braces:

// src/App.jsx
export default function App() {
  const logo = '/vite.svg';
 
  return <img src={logo} alt="Logo" width={64} />;
}

The image vite.svg lives in public/, so it is available at /vite.svg.

Differences from HTML

Some attributes have other names, because JSX is JavaScript and class and for are taken there:

HTMLJSX
classclassName
forhtmlFor
onclickonClick
tabindextabIndex

Also, every tag must be closed: <br />, <img />, <input />.

One root element

A component returns one element. If an extra div is not wanted, use a fragment — the empty tags <> and </>:

// src/App.jsx
export default function App() {
  return (
    <>
      <h1>My tasks</h1>
      <p>Things to do today.</p>
    </>
  );
}

A fragment groups elements but does not reach the page itself: in the developer tools you see only h1 and p.

Comments

A comment inside markup is also written in curly braces: {/* text */}.

Common mistake

The style attribute takes an object, not a string. That is why there are two pairs of braces: the outer ones are JSX, the inner ones are the object.

// Wrong: <p style="color: red">Error</p>
 
function ErrorText() {
  return <p style={{ color: 'red', fontSize: 14 }}>Error</p>;
}

Property names are written in camelCase: fontSize, not font-size.

Thanks for reading!

Donate to the site — we work hard for you.