JSX stands for Javascript XML formally known as (Javascript Syntax Extension) and is used to define what the UI should look like.
JSX is a syntax extension for JavaScript that looks similar to XML or HTML and makes it easier to write and visualize the structure of React components.
Once we have defined our JSX elements, React will render them to the actual DOM.
Components are the building blocks of a React application. We can create functional components or class components.
// Your Functional Component const YourComponent = () => { return <p>Hello World, JSX Rendering!</p>; };
Within our component, we can use JSX to define the UI structure. JSX elements represent React elements.
const YourComponent = () => { const fullName = "Alice Collin"; return ( <div> <h1>Hi, {fullName}</h1> <article>This is a Article.</article> </div> ); }; export default YourComponent;
To render our React component with JSX to the actual DOM, after v18.0.0. we have to use the `createRoot` function.
This function takes one argument: The targeted DOM element where you want to render it, and through it, we get the `render` function which Reacts element you want to render.
import React from 'react'; import { createRoot } from 'react-dom/client'; const container = document.getElementById('root'); const root = createRoot(container); const YourComponent = () => { return ( <div> <article>This is a Article.</article> </div> ); }; root.render(<YourComponent />);
The YourComponent is being rendered into the HTML element with the ID 'root'.
React components can update their state, props, or other variables over time. When this happens, React automatically re-renders the component, updating the JSX in the DOM.
import React, { Component } from "react; class CustomCountComponent extends Component { constructor() { super(); this.state = { count: 0 }; } decrement = () => { this.setState({ count: this.state.count - 1 }); }; increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <button onClick={this.decrement}>-</button> <h2>Count: {this.state.count}</h2> <button onClick={this.increment}>+</button> </div> ); } } export default CustomCountComponent;
when the `increment` or `decrement` method is called, it will update the current `count` state and React detect changes and automatically re-renders the component with the updated state `count` value.
JSX elements are eventually transformed into Javascript objects called React elements, which are then used to update the virtual DOM.
React compares the virtual DOM with the actual DOM and efficiently updates only the parts of the DOM that have changed and this process is called reconciliation.