Skip to content

Expert · React concepts · topic 56 of 64 · 35 min

Why React: components and JSX

Explanation

React is a JavaScript library for building user interfaces from small, reusable pieces called components. A component is a function that takes data and returns what that part of the screen should look like, written in JSX. When the data changes, React updates the page for you. Start a new project with Vite, or with a framework such as Next.js.

Why React?

In the DOM module you changed the page by hand: find an element, change its text, add a class, append a new item. That is fine for a small page. In a big app, such as a food delivery app with a menu, filters, offers and a cart, keeping every part of the screen in step with the data by hand becomes slow to write and easy to get wrong.

React turns the idea around. You describe what the screen should look like for the current data, and React works out which DOM changes are needed. People say the UI (user interface) is a function of the data: same data in, same screen out.

Think of it like this: Think of the scoreboard at a cricket ground. The old way is a worker who climbs up and changes each number plate by hand after every ball: easy to forget one. React is like a digital scoreboard: you send it the new score (the data), and it redraws whatever changed. You never touch the plates yourself.

Components

A component is a JavaScript function whose name starts with a capital letter and which returns JSX (HTML-like markup). You use it like an HTML tag: <ProductCard />. Components can use other components, so a whole page becomes a tree of components.

javascript
function ProductCard() {
  return (
    <div className="card">
      <h2>Rice 5 kg</h2>
      <p>Rs 320</p>
    </div>
  );
}

export default function App() {
  return (
    <main>
      <h1>Sharma Kirana</h1>
      <ProductCard />
      <ProductCard />
    </main>
  );
}
Two components: App uses ProductCard twice (React code, runs in a React project)
output
App
|-- Header
|-- ProductList
|     |-- ProductCard  (one for each product)
|-- Cart
      |-- CartLine     (one for each item)
A component tree: the page is built from small pieces inside bigger ones

JSX rules

JSX looks like HTML inside JavaScript. A build tool (such as Vite) turns it into normal JavaScript function calls before the browser runs it. A few rules are different from HTML:

RuleHTMLJSX
Return one parent element (or a fragment)Many top-level tags are fine<>...</> or one wrapping <div>
CSS classclass="card"className="card"
Label for an inputfor="pin"htmlFor="pin"
Attribute namesonclick, tabindexcamelCase: onClick, tabIndex
Every tag must close<img src="a.png"><img src="a.png" />
Inline stylestyle="color: red"style={{ color: 'red' }} (an object)
JavaScript valuesNot possibleInside curly braces: {price * qty}
javascript
function OrderSummary() {
  const name = 'Asha';
  const items = 3;
  const total = 480;
  return (
    <>
      <h2>Hello, {name}</h2>
      <p className="muted">{items} items, total Rs {total}</p>
      <label htmlFor="note">Note for the delivery partner</label>
      <input id="note" />
    </>
  );
}
A fragment <>...</> groups elements without adding an extra div; {} inserts a JavaScript value (React code, runs in a React project)
Careful: Inside { } you can put an expression, which is anything that gives a value: a variable, a sum, a function call or a ternary. You cannot put a statement such as if or for inside JSX. Do that work before the return, or use a ternary or map, which you will meet soon.

Starting a React project

The official site, react.dev, recommends starting a full app with a framework such as Next.js or React Router, because they add pages (routing) and data loading. To learn React, or for a simple single-page app, Vite is a fast and popular build tool. Create React App (create-react-app) is deprecated: do not use it for new projects, even though many old tutorials do.

bash
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
Create and start a React project with Vite (you need Node.js installed)

Vite makes a few files for you. index.html has an empty <div id="root">. src/main.jsx tells React to take over that div. src/App.jsx is your first component. When you save a file, the browser updates at once.

javascript
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
);
src/main.jsx: React draws App inside the root div (React code, runs in a React project)
Tip: Install the React Developer Tools extension for Chrome, Edge or Firefox. It adds a Components tab to DevTools, where you can see the component tree and the props and state of each component, and a Profiler tab to see what re-rendered.

Modern React (React 19) uses function components and hooks. Older code and tutorials use class components (class Cart extends React.Component). You may see them at work, but write new code with functions.

Watch the lesson

Why React: components and JSX · 1/7

React = build UIs from components

Today we meet React, the most used library for building user interfaces.

Prefer a video by a teacher? Find free videos on “react tutorial for beginners components jsx vite” on YouTube ↗

In real life: A restaurant page in a food delivery app

A restaurant page is built from components: RestaurantHeader (name, rating, delivery time), MenuSection for each category, DishCard used once for every dish, and CartButton at the bottom. The team writes DishCard once and React draws it 60 times from the menu data. When you add a dish, only the data changes; React updates the count on CartButton for you.

Practice (0/3 done)

Task 1 · Code · Javascript

JSX is not magic. A build tool turns <h2 className="title">Rice</h2> into a function call like h("h2", { className: "title" }, "Rice"), and that call returns a plain object that describes the element. Write a simple version: h(type, props, ...children) returns { type, props } where props is a NEW object with all the given props plus a children array. If props is null, start from an empty object. Example: h("p", null, "Rs ", 320) returns { type: "p", props: { children: ["Rs ", 320] } }.

Task 2 · Code · Javascript

React turns the tree of element objects into real page content. Write renderToString(node) that turns a node into an HTML string. Rules: (1) null, undefined, true and false render nothing (""). (2) A string or number renders as text, with & < > replaced by &amp; &lt; &gt; (React escapes text like this, which is why showing user text in JSX is safe). (3) An element { type, props } renders as <type attrs>children</type>. Every prop except children becomes name="value", in the order given, but className is written as class and htmlFor as for. Children (props.children, may be missing) are rendered with the same rules and joined. Example: renderToString({ type: "p", props: { className: "price", children: ["Rs ", 320] } }) returns '<p class="price">Rs 320</p>'.

Task 3 · Practice

Create your first React project with Vite: npm create vite@latest my-shop -- --template react, then npm install and npm run dev. Replace App.jsx with your own page: a ShopHeader component and a ProductCard component that App uses three times. Install React Developer Tools in your browser and find your components in the Components tab.

Quick quiz

Question 1

1.What does "the UI is a function of the data" mean in React?

Question 2

2.How do you give a JSX element the CSS class "card"?

Question 3

3.A component returns <h1>Menu</h1><p>Today's dishes</p> and gives an error. What is the fix?

Question 4

4.Which way of starting a new React project is deprecated and should not be used today?

Question 5

5.Why must a component name start with a capital letter, like ProductCard?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: TypeScript in real projects