To avoid the pain of imperative programming in JavaScript, that is, to manipulate HTML DOM elements using the rudimentary JavaScript DOM API, React introduced a syntax called JSX. This syntax allows HTML-like markups to be decoratively embedded inside JavaScript code. You describe what should be on the screen, and React figures out the rest.
Babel and TypeScript can compile JSX into regular JavaScript functions that web browsers understand, without needing React outside the development environment.
The JSX transformer will turn code like this:
function App() {
return <h1>Hello World</h1>;
}
Into this:
// Inserted by a compiler (don't import it yourself!)
import { jsx as _jsx } from 'react/jsx-runtime';
function App() {
return _jsx('h1', { children: 'Hello world' });
}
With the introduction of JSX, React Components bear strong similarities to HTML, including markup syntax, how they are composed, and the ability to nest components. To distinguish React components from regular HTML tags, a React component name must start with a capital letter and use camel case. E.g., <Header />
instead of <header />
. React treats lowercase tags as regular HTML tags by default. In addition, adjacent JSX tags must be wrapped inside a single parent tag in each component. You can use the empty tag <>
and </>
(a shorthand version of the <Fragment>
component) to avoid unnecessarily extra tags.
You can use the { }
(curly brackets) to insert JavaScript code inside JSX markup to display data, which works similarly to most web scripting languages, such as PHP or ASP.
return (
<h1 id={article.id} className="article hero">
{article.title}
</h1>
);