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

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.

React Homepage


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

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:

  1. Single parent node per return statement.
  2. Use camelCase for DOM props (className, onClick).
  3. 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.

ConceptMeaningImmutable?How to update
PropsExternal 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.
StateInternal, 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.

CommandWhen to run itWhat it does
npm run devDevelopment time (first).Launches Vite dev‑server with Hot Module Reloading at http://localhost:5173. Leave this terminal open while editing.
npm testAfter or during dev.Executes Jest + Testing‑Library suites; shows pass/fail & generates coverage.
npm run lintBefore commit / CI.Runs ESLint + Prettier checks; auto‑fixes style issues when possible.
npm run buildWhen you’re ready to publish.Produces an optimized static bundle in dist/ using Vite’s Rollup pipeline.
npm run previewFinal smoke‑test.Serves the built dist/ bundle locally to verify production behaviour.

Typical workflow

  1. npm run dev (in terminal A) – keep running.
  2. Edit code → browser auto‑refreshes.
  3. In terminal B run npm test --watch to re‑run tests on save.
  4. 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.

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:

  1. Project dashboard shows • Bugs • Vulnerabilities • Code Smells.
  2. Coverage gauge reflects Jest LCOV (target ≥ 80 %).
  3. Quality Gate status (green = passed).

1.5.6 CI/CD Integration Example (GitHub Actions)

CI/CD = Continuous Integration / Continuous Delivery (or Deployment).

Why bother?

  1. Immediate feedback loop – catch bugs before they hit teammates.
  2. Repeatable builds – the same machine‑readable script runs everywhere.
  3. Ship faster – no more “works on my machine”.

Step‑by‑Step Setup

  1. Create workflow file:
    mkdir -p .github/workflows && touch .github/workflows/ci.yml
  2. 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

What you should see

| Stage | Expected Output | |——-|—————–| | checkout | “Checked out @ " | | setup‑node | "Using Node v22.x" | | tests | Jest summary + `Coverage ≥90 %` | | SonarCloud | Quality Gate status in PR comment |

1.6 Next Steps