JSX Basics
JSX (JavaScript XML) is a syntax extension for JavaScript often used with React to describe what the UI should look like. It allows you to write HTML-like code within JavaScript files, which React then transforms into actual DOM elements.
- Syntax: JSX looks similar to HTML but has some differences. For example:
const element = Hello, world!
;
- Expressions: You can embed JavaScript expressions inside JSX using curly braces {}:
const name = 'Tina';
const element = Hello, {name}
;
- JSX allows nesting elements:
const element = (
Hello, world!
This is a paragraph.
);
Rendering in React
1. Creating a React Element:
React elements are the building blocks of React applications. They describe what you want to see on the screen:
const element = Hello, world!
;
2. Rendering an Element to the DOM:
Use ReactDOM.render() to render a React element into a DOM container:
import React from 'react';
import ReactDOM from 'react-dom';
const element = Hello, world!
;
ReactDOM.render(element, document.getElementById('root'));
3. Components:
Components are reusable, self-contained pieces of code that return React elements. They can be either class-based or function-based:
Function Component:
function Welcome(props) {
return Hello, {props.name}
;
}
Class Component:
class Welcome extends React.Component {
render() {
return Hello, {this.props.name}
;
}
}
4. Props:
Props (short for properties) are how you pass data to components:
function App() {
return ;
}
5. State:
State is used to manage data within a component that can change over time:
function Counter() {
const [count, setCount] = React.useState(0);
return (
You clicked {count} times
);
}