JSX (JavaScript XML) is a syntax extension for JavaScript commonly used with React to describe what the UI should look like. Here are the basics:
JSX allows you to write HTML-like code directly in your JavaScript files. This makes it easier to visualize the UI structure and helps in building the component hierarchy.
You can embed JavaScript expressions inside JSX by wrapping them in curly braces {}.
const name = 'World';
const element = <h1>Hello, {name}!</h1>;
JSX attributes are similar to HTML attributes but follow camelCase naming conventions for JavaScript compatibility.
const element = <img src="image.jpg" alt="Image description" />;
You can nest elements inside other elements just like in HTML.
const element = (
<div>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</div>
);
JSX compiles down to regular JavaScript objects using tools like Babel. This means you can use JSX inside functions, loops, and conditionals.
function greeting(user) {
if (user) {
return <h1>Hello, {user.name}!</h1>;
}
return <h1>Hello, Stranger!</h1>;
}
You can specify child elements either as nested elements or as an array of elements.
const element = (
<div>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</div>
);
// Or as an array
const element = (
<div>
{[<h1 key="1">Hello, World!</h1>, <p key="2">This is a paragraph.</p>]}
</div>
);
Components can be defined as JavaScript functions or classes and used within JSX.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
const element = <Welcome name="Sara" />;
There are a few key differences between JSX and HTML:
Class vs. className: Use className instead of class.
Self-closing Tags: Tags like <img /> must be self-closed.
camelCase Property Naming: Use camelCase for event handlers (e.g., onClick).
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<h1>Welcome to React</h1>
<p>This is a simple React component using JSX.</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));