React JS Complete Guide
Audience: Absolute beginners with zero JavaScript experience. Follow step‑by‑step instructions on a Windows, macOS, or Linux machine.
1.1 What Is React?
1.1.1 One‑Sentence Definition
React JS is an open‑source JavaScript library for building user interfaces by composing reusable components.
1.1.2 Key Features
- Virtual DOM — efficient UI updates without manually manipulating the browser DOM.
- Component Model — build screens by nesting small, testable pieces of UI.
- Declarative syntax (JSX) — describe what the UI should look like; React handles how to render it.
- Hooks — functional APIs like
useState
&useEffect
for state and side‑effects. - Cross‑platform — power web, native (React Native), desktop (Tauri), VR, etc.
1.1.3 When to Use React
Choose React when you need rich, interactive UIs, a large ecosystem, or server‑side rendering (Next.js). Skip it for static pages where vanilla HTML/CSS suffices.
1.2 Environment Setup
1.2.1 Prerequisites
| Tool | Minimum Version | Purpose | |——|—————–|———| | Node.js | 18 LTS or newer | Runs dev server, bundles app | | npm / pnpm / yarn | ships with Node | Package manager | | Code Editor (VS Code) | Latest | Syntax highlighting, linting |
Download Node LTS → https://nodejs.org/en/download.
Verify installation:
node -v # v22.x.x
npm -v # 10.x.x
1.2.2 Starter Scaffolds Explained
- Create React App (CRA) ‑ The historic Facebook starter. Bundles webpack + Babel. Status: maintenance‑only (no new features).
- Vite ‑ Lightning‑fast dev server & build tool. Uses native ES modules & Rollup. Recommended for new projects.
Why choose Vite? Zero‑config, instant Hot‑Module‑Reload, smaller bundles.
1.2.3 Create Your First React App with Vite (TypeScript)
# 1 Create project
npm create vite@latest my-react-app -- --template react-ts
cd my-react-app
# 2 Install dependencies
npm install # or pnpm install
# 3 Start dev server
npm run dev # ➜ http://localhost:5173 (auto‑opens)
What each command does: | Step | Explanation | |——|————| | npm create vite
| Downloads Vite CLI & scaffolds folder structure. | | --template react-ts
| Uses official React + TypeScript template. | | npm install
| Pulls React 19.x, Vite, TypeScript, @types packages. | | npm run dev
| Launches Vite in development mode with Hot Reload. |
1.2.4 Project Directory Walk‑Through
my-react-app/
├─ public/ # static assets copied as‑is
├─ src/
│ ├─ App.tsx # root component
│ ├─ main.tsx # entry point → mounts <App />
│ └─ vite-env.d.ts# TS helpers for import.meta
├─ index.html # single root HTML
├─ package.json # scripts & deps
└─ tsconfig.json # TypeScript compiler settings
1.3 React Fundamentals
1.3.1 JSX Syntax
JSX lets you write HTML‑like syntax inside JavaScript.
const title = <h1>Hello React ⚛️</h1>; // JSX element
Rules:
- Single parent node per return statement.
- Use camelCase for DOM props (
className
,onClick
). - Insert variables with
{ }
braces.
1.3.2 Building Your First Component
// src/components/Counter.tsx
import { useState } from 'react'; // React hook
/**
* Counter ‑ clickable button that increments a number.
*/
export default function Counter() {
// Declare "count" state variable, initial 0
const [count, setCount] = useState<number>(0);
// JSX to render
return (
<>
{/* Display current count */}
<p data-testid="count">Count: {count}</p>
{/* Update state on click */}
<button
onClick={() => setCount(c => c + 1)}
style=
>
Increment
</button>
</>
);
}
Line‑by‑line explanations are inline as comments (/** … */
).
1.3.3 Props & State Cheat‑Sheet
A “cheat‑sheet” is a compact reference; keep this open while coding.
Concept | Meaning | Immutable? | How to update |
---|---|---|---|
Props | External data passed into a component by its parent. | Yes – never mutate; treat as read‑only. | You cannot change props inside the child; instead ask parent to pass new ones. |
State | Internal, local, time‑varying data that determines what the component renders. | No – but you must update via the setter to trigger a re‑render. | const [count,setCount]=useState(0); setCount(prev=>prev+1); |
Rule of thumb: If the data changes inside the component → state.
If the data comes from parent and does not change internally → props.
Quick API reminders:
// Props: define interface for TS
interface ButtonProps { label: string; onClick?: () => void; }
export function Button({ label, onClick }: ButtonProps) {
return <button onClick={onClick}>{label}</button>;
}
// State: useState()
const [value, setValue] = useState<string>('hello');
1.3.4 Running Scripts
Once dependencies are installed (npm install
) you’ll use npm scripts defined in package.json
. Run them sequentially as needed, not all at once.
Command | When to run it | What it does |
---|---|---|
npm run dev | Development time (first). | Launches Vite dev‑server with Hot Module Reloading at http://localhost:5173 . Leave this terminal open while editing. |
npm test | After or during dev. | Executes Jest + Testing‑Library suites; shows pass/fail & generates coverage. |
npm run lint | Before commit / CI. | Runs ESLint + Prettier checks; auto‑fixes style issues when possible. |
npm run build | When you’re ready to publish. | Produces an optimized static bundle in dist/ using Vite’s Rollup pipeline. |
npm run preview | Final smoke‑test. | Serves the built dist/ bundle locally to verify production behaviour. |
Typical workflow
npm run dev
(in terminal A) – keep running.- Edit code → browser auto‑refreshes.
- In terminal B run
npm test --watch
to re‑run tests on save. - Before pushing:
npm run lint && npm run build
to ensure clean build.
1.4 Unit Testing React Components
1.4.1 Why Test?
Catch regressions, document behaviour, enable refactors.
1.4.2 Install Testing Stack
npm i -D jest @testing-library/react @testing-library/jest-dom \
@testing-library/user-event ts-jest jest-environment-jsdom
1.4.3 Configure Jest (jest.config.ts
)
import { pathsToModuleNameMapper } from 'ts-jest';
import tsconfig from './tsconfig.json';
export default {
preset: 'ts-jest', // transpile TS → JS on the fly
testEnvironment: 'jsdom', // browser‑like environment
moduleNameMapper: pathsToModuleNameMapper(tsconfig.compilerOptions.paths),
setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
collectCoverage: true,
coverageReporters: ['text', 'lcov'],
};
1.4.4 Write Your First Test
// src/components/Counter.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Counter from './Counter';
describe('<Counter>', () => {
it('increments count on click', async () => {
render(<Counter />);
const btn = screen.getByRole('button', { name: /increment/i });
await userEvent.click(btn);
expect(screen.getByTestId('count')).toHaveTextContent('1');
});
});
Run tests & coverage:
npm test # Jest watch mode
npm test -- --coverage
1.5 Static Code Quality with SonarQube
1.5.1 What Is SonarQube?
SonarQube is a continuous inspection platform that analyzes source code for bugs, code smells, security vulnerabilities, and test coverage. It produces a dashboard and enforces Quality Gates to stop bad code from shipping.
- Official site: https://www.sonarsource.com/products/sonarqube/
- Community Edition download: https://www.sonarsource.com/products/sonarqube/downloads/
- Documentation: https://docs.sonarsource.com/sonarqube/latest/
1.5.2 Installation Options
| Option | Command | |——–|———| | Docker (quick) | docker pull sonarqube:community
| | ZIP installer | Download → unzip → bin/<os>/sonar.sh start
|
Docker is simplest: container includes PostgreSQL & web UI.
1.5.3 Run SonarQube in Docker
docker run -d --name sonarqube -p 9000:9000 sonarqube:community
# UI ➜ http://localhost:9000 (login admin/admin → change password)
1.5.4 Install SonarScanner in Your Project
npm i -D sonarqube-scanner
Create sonar-project.properties
:
sonar.projectKey=my-react-app
sonar.sources=src
sonar.tests=src
sonar.test.inclusions=**/*.test.tsx,**/*.test.ts
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.typescript.tsconfigPath=tsconfig.json
1.5.5 Run Analysis Locally
npm test -- --coverage # generates coverage/lcov.info
npx sonar-scanner # uploads data to SonarQube server
Expected results:
- Project dashboard shows • Bugs • Vulnerabilities • Code Smells.
- Coverage gauge reflects Jest LCOV (target ≥ 80 %).
- Quality Gate status (green = passed).
1.5.6 CI/CD Integration Example (GitHub Actions)
CI/CD = Continuous Integration / Continuous Delivery (or Deployment).
- Continuous Integration (CI) automatically runs your tests & static checks on every commit so broken code never lands in
main
. - Continuous Delivery (CD) automatically builds the production bundle and, if you choose, deploys it to hosting after CI passes.
Why bother?
- Immediate feedback loop – catch bugs before they hit teammates.
- Repeatable builds – the same machine‑readable script runs everywhere.
- Ship faster – no more “works on my machine”.
Step‑by‑Step Setup
- Create workflow file:
mkdir -p .github/workflows && touch .github/workflows/ci.yml
- Paste the template below (replace
<project-key>
if you use SonarCloud).
name: CI
on:
push:
branches: [ main ]
pull_request:
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# 1. Set up Node (tool‑cache)
- uses: actions/setup-node@v4
with:
node-version: '22' # LTS
cache: 'npm'
# 2. Install deps & run linters/tests
- run: npm ci
- run: npm run lint
- run: npm test -- --coverage
# 3. Upload coverage report to GitHub summary
- uses: actions/upload-artifact@v4
with:
name: coverage
path: coverage
# 4. (Optional) Static analysis in SonarCloud
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@v2
env:
SONAR_TOKEN: $
with:
projectKey: <project-key>
How to run it
- Commit & push ➜ GitHub → Actions tab shows a new workflow run.
- Green check ✓ = all steps succeeded. Red × = investigate logs.
What you should see
| Stage | Expected Output | |——-|—————–| | checkout | “Checked out @
1.6 Next Steps
- Dive into official React tutorials ➜ https://react.dev/learn.
- Explore state management (Redux, Zustand, Jotai).
- Try React Router for navigation.
- Extend testing with Cypress (E2E) and msw (mock API).
- Host your site on Vercel or Netlify.