Lesson 1 of 11 · 11 min · Components
React basics: JSX and components
What you will learn
- What React is and the mental model: UI as a function of data
- Create a project with Vite
- Write function components and use them like HTML tags
- The rules of JSX: expressions, attributes, fragments,
className - Style components and organise files
In simple words
React is a JavaScript library for building user interfaces out of small reusable pieces called components. Instead of finding elements on the page and changing them by hand, you describe what the screen should look like for the current data, and React updates the page to match whenever the data changes. A component is just a function that returns a piece of that description.
Words to know
- Component: a reusable piece of the interface, written as a JavaScript function.
- JSX: the HTML-like syntax used inside JavaScript to describe the interface.
- Render: React calling your component to find out what to show.
- Props: the inputs a component receives from its parent (next lesson).
The mental model
With plain JavaScript you write instructions: "find this element, set its text, add that class". As the app grows, you lose track of what the screen currently shows. React asks you to write the opposite: the UI is a function of state.
UI = component(props, state)
You describe what each piece looks like for the current data. When the data changes, React runs your components again, compares the new description with the previous one (reconciliation), and updates only the parts of the real DOM that differ. You almost never touch the DOM yourself.
Create a project
Use Vite, a fast build tool (the React team no longer recommends Create React App, which is deprecated). For a full-featured framework, React recommends options such as Next.js or React Router's framework mode; this course uses plain React with Vite so you see the fundamentals.
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev # opens http://localhost:5173 with instant hot reload
You need Node.js (a current LTS release). The project contains index.html (the page with <div id="root">), src/main.tsx (starts React) and src/App.tsx (your first component):
// src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
);
StrictMode runs extra checks in development (it renders components twice to reveal impure code); it has no effect in production.
A component
A component is a function whose name starts with a capital letter and returns JSX:
function Greeting() {
return <h1>Hello, React</h1>;
}
export default function App() {
return (
<main>
<Greeting />
<Greeting />
</main>
);
}
Use it like an HTML tag: <Greeting />. Capital letters tell React that it is a component (lowercase <div> is a built-in HTML element). Each use creates an independent instance. Components can contain other components, forming a tree with App at the root.
JSX
JSX looks like HTML but is JavaScript: a build tool compiles it into function calls. The rules:
1. Return a single root element. Wrap siblings in a parent or a fragment (<>...</>, which adds no extra element to the page):
return (
<>
<h1>Courses</h1>
<p>Pick one.</p>
</>
);
2. Close every tag, including <img />, <input /> and <br />.
3. Use camelCase attributes. class becomes className, for becomes htmlFor, tabindex becomes tabIndex, onclick becomes onClick. Attributes such as aria-label and data-id keep their hyphens.
<label htmlFor="q">Search</label>
<input id="q" className="field" type="search" aria-label="Search courses" />
4. Put JavaScript in curly braces:
function Welcome() {
const name = "Asha";
const credits = 3;
const imageUrl = "/avatar.png";
return (
<section>
<h2>Welcome, {name}!</h2>
<p>You have {credits * 2} points.</p>
<img src={imageUrl} alt={`Photo of ${name}`} width={64} height={64} />
<p style={{ color: "navy", fontSize: 18 }}>Inline styles take an object.</p>
<p>{new Date().toLocaleDateString("en-IN")}</p>
</section>
);
}
{ } can hold any JavaScript expression (a value), not statements (if, for): use a ternary or && (next lessons) or compute the value before the return. Attribute values: a quoted string "text" or an expression {value}.
5. Text is escaped automatically. React protects against XSS by treating strings as text, not HTML: {userInput} is safe. The prop dangerouslySetInnerHTML bypasses this and is named to warn you; sanitise anything you pass it.
6. Comments inside JSX: {/* a comment */}.
JSX is optional syntax (React.createElement or the compiled jsx() calls are what it becomes), but everyone uses it.
Components should be pure
A component must be a pure function of its inputs: the same props and state give the same JSX, and rendering must not change anything outside: no modifying variables created outside the component, no changing the DOM, no network calls while rendering. React may render a component several times (StrictMode, concurrent features), and skipping or repeating a render must be safe. Put side effects in event handlers or in effects (later lessons).
let counter = 0;
function Bad() {
counter++; // mutating an outside variable during render: impure
return <p>{counter}</p>;
}
Organising components
- One component per file is common:
src/components/CourseCard.tsx, with a default or named export; keep tiny helpers next to their parent. - Name files and components in
PascalCase. - Split a component when it gets large, when a part repeats or when a part has its own state or purpose, but do not split to the point of confusion.
- Never define a component inside another component's body: it is recreated on every render, losing its state.
// CourseCard.tsx
type CourseCardProps = { title: string; level: string };
export function CourseCard({ title, level }: CourseCardProps) {
return (
<article className="card">
<h3>{title}</h3>
<p>{level}</p>
</article>
);
}
// App.tsx
import { CourseCard } from "./components/CourseCard";
export default function App() {
return (
<main>
<CourseCard title="SQL for analysts" level="Beginner" />
<CourseCard title="Spring Boot" level="Intermediate" />
</main>
);
}
Styling
- Plain CSS with
className, imported in the component:import "./CourseCard.css";. - CSS Modules (
CourseCard.module.css): class names are scoped automatically:import styles from "./CourseCard.module.css"; <div className={styles.card}>. - Utility CSS such as Tailwind CSS.
- CSS-in-JS libraries exist but have shrunk in popularity because of run-time cost.
- Keep markup semantic and accessible (previous lessons): React does not do that for you.
Dev tools and habits
- Install the React Developer Tools browser extension to inspect the component tree, props and state.
- Use ESLint (Vite's template configures
eslint-plugin-react-hooks), Prettier and TypeScript; they catch the common mistakes. - Check the console for warnings (missing keys, invalid DOM nesting, hydration issues).
- The React Compiler (stable since late 2025) can automatically optimise re-renders at build time, so you will write less manual memoisation than older tutorials show.
Common mistakes
- Lowercase component names (
<greeting />is treated as an HTML tag). - Using
classandforinstead ofclassNameandhtmlFor. - Returning several sibling elements without a wrapper or fragment.
- Using statements inside
{ }. - Defining components inside other components.
- Impure renders (mutating outside values, fetching inside the render body).
- Using
dangerouslySetInnerHTMLwith unsanitised data.
Try it yourself
- Create a Vite React TypeScript project and run it.
- Write a
CourseCardcomponent and render it three times with different content (hard-coded for now). - Use JSX expressions: show today's date in the Indian format and a computed value.
- Break each JSX rule on purpose (two roots,
class, unclosed<img>) and read the error. - Move the card into its own file and import it, and install React Developer Tools to inspect it.
Check yourself
What is JSX?
A syntax extension that lets you write HTML-like markup inside JavaScript; build tools compile it into function calls that create React elements.
Why must component names start with a capital letter?
React treats lowercase tags as built-in HTML elements and capitalised ones as your own components.
What does it mean for a component to be pure?
For the same props and state it returns the same JSX and has no side effects while rendering, so it is safe for React to render it more than once.
What can go inside the curly braces of JSX?
Any JavaScript expression, such as a variable, a calculation, a function call or a ternary, but not statements like if or for.
Interview questions
What is React and why use it?
A library for building UIs from components. You describe the UI for the current state, and React efficiently updates the DOM, which makes interfaces easier to reason about, reuse and test than manual DOM manipulation.
What is the virtual DOM?
A lightweight in-memory description of the UI; React compares the new description with the previous one and applies only the differences to the real DOM (reconciliation).
What is the difference between a fragment and a div wrapper?
A fragment groups elements without adding an extra node to the DOM, avoiding unnecessary wrappers that can break layouts and semantics.
Summary
- React builds UIs from components; the UI is a function of data, and React updates the DOM when data changes.
- Create projects with Vite; components are capitalised functions returning JSX.
- JSX rules: one root (or fragment), closed tags,
className, expressions in braces, escaped text. - Keep components pure, small and in their own files; style with CSS, modules or utilities.
Going deeper
- React: Quick Start: the official tutorial and concepts.
- React: Your first component: components and JSX basics.
- React: Writing markup with JSX: the rules of JSX.
- React: Keeping components pure: why purity matters.
See how much of this you can explain
A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.