Flat Preloader Icon

JSX and Rendering

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 = <h1>Hello, world!</h1>;

				
			
  • Expressions: You can embed JavaScript expressions inside JSX using curly braces {}:
				
					const name = 'Tina';
const element = <h1>Hello, {name}</h1>;

				
			
  • JSX allows nesting elements:
				
					const element = (
  <div>
    <h1>Hello, world!</h1>
    <p>This is a paragraph.</p>
  </div>
);

				
			

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 = <h1>Hello, world!</h1>;

				
			

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 = <h1>Hello, world!</h1>;

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 <h1>Hello, {props.name}</h1>;
}

				
			

Class Component:

				
					class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

				
			

4. Props:

Props (short for properties) are how you pass data to components:
				
					function App() {
  return <Welcome name="Tina" />;
}

				
			

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 (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}