How to Write JSX in React: Syntax and Examples
In React, you write
JSX by embedding HTML-like syntax inside JavaScript functions or components. JSX lets you describe UI elements clearly and React converts it into real DOM elements behind the scenes.Syntax
JSX looks like HTML but is written inside JavaScript. You use tags like <div> or <h1> to create elements. You can embed JavaScript expressions inside curly braces { }. Each JSX expression must have one parent element.
jsx
function Greeting() { return ( <div> <h1>Hello, world!</h1> <p>Welcome to React JSX.</p> </div> ); }
Example
This example shows a simple React component using JSX to render a greeting message. It returns a div with a heading and a paragraph.
jsx
import React from 'react'; import { createRoot } from 'react-dom/client'; function Greeting() { return ( <div> <h1>Hello, world!</h1> <p>Welcome to React JSX.</p> </div> ); } const container = document.getElementById('root'); const root = createRoot(container); root.render(<Greeting />);
Output
Hello, world!
Welcome to React JSX.
Common Pitfalls
- JSX must have one parent element; multiple sibling elements need to be wrapped in a container like
<div>or<React.Fragment>. - JavaScript expressions inside JSX must be wrapped in curly braces
{ }. - Use
classNameinstead ofclassfor CSS classes. - Self-close tags like
<img>or<br>must end with a slash:<img />.
jsx
/* Wrong: multiple siblings without a parent */ function Wrong() { return ( <> <h1>Hello</h1> <p>World</p> </> ); } /* Right: wrapped in a div */ function Right() { return ( <div> <h1>Hello</h1> <p>World</p> </div> ); }
Quick Reference
| JSX Feature | Description | Example |
|---|---|---|
| Element Tags | Use HTML-like tags to create elements | Hello |
| JavaScript Expressions | Embed JS inside curly braces | {userName} |
| Attributes | Use camelCase for attributes like className | |
| Self-closing Tags | Close tags like | ![]() |
| Fragments | Group siblings without extra nodes | <>...> or |
Key Takeaways
JSX lets you write HTML-like code inside JavaScript for React components.
Always wrap multiple JSX elements in one parent container or fragment.
Use curly braces {} to insert JavaScript expressions inside JSX.
Use className instead of class for CSS classes in JSX.
Self-close tags like
and
with a slash to avoid errors.
with a slash to avoid errors.
