Intro

  • React is a javascript library for building dynamic and interactive user interfaces
  • Typescript is a superset of js that adds static typing to the language and helps catch errors earlier in the development process

React Tutorial

Set up the development environment

  • Check whether have node v16 or higher
node -v
v20.11.1

Create React App

Can use the official tool, create React App (CRA) or Vite, which is much faster and provides smaller bundle sizes

  • Create React app using Vite
    • project name: react-app
    • framework: React
    • variant: TypeScript
npm create vite@4.1.0
  • Open embedded terminal (ctrl + `), cd into the new folder, install 3rd party dependencies, and run the web server
    • Can also use npm i instead of npm install
  cd react-app
  npm install
  npm run dev

Project structure

  • Folders
    • node_modules: 3rd party libraries like React are installed
    • public: contains public assets like image files
    • srs
      • contians App component App.tsx
    • index.html
      • a div with id=“root”: container for our app
      • script with src=“/scr/main.tsx” references entry point for the app
    • package.json: contains info about the project
      • name
      • version
      • dependencies
      • development dependencies (not used for deployment)
    • tsconfig.json: typescript configuration file
      • settings for telling typescript compiler how to compile the code to javascript
    • vite.config.ts

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

Create a React component

Can use a Javascript class or function to create a react component. Function-based components using PascalCasing are the recommended approach.

JSX stands for JavaScript XML. It’s a syntax extension for JavaScript that allows you to write HTML-like structures within your JavaScript code. JSX is primarily used with React, a popular JavaScript library for building user interfaces.

picture 0
Shows you how JSX (JavasSript XML) gets compiled into JavaScript.

  • Create Message component Message.tsx
// PascalCasing
function Message() {
    // JSX: javascript XML
    return <h1>Hello World</h1>;
}
 
export default Message;
  • Create App component with a div containing the Message component
import Message from './Message'
 
// HMR (Hot Module Replacement)- auto-refresh page in browser
 
function App() {
  // Return Message component
  return <div><Message /></div>
}
 
export default App;
  • In the terminal, can see the web server is still running

    • Vite monitors our files for changes and auto-refreshes the page in the browser
    • hrm (hot module replacement)
  • Use JSX to create dynamic content

// PascalCasing
function Message() {
    // JSX: javascript XML
    const name = 'Chris';
    if (name)
        return <h1>Hello {name}</h1>
    return <h1>Hello World</h1>;
}
 
export default Message;

How React works

  • React creates a JavaScript data structure called Virtual DOM

    • A lightweight, in-memory representation of the component tree, where each node represents a component and its properties
    • When the state (data) of a component changes, React updates the corresponding node in the virtual DOM
    • then React DOM updates the corresponding nodes in the actual DOM
  • How the component tree is rendered in an element with id ‘root’

    • can also be rendered in a mobile app using React Native

main.tsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
 
createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

Building components

  • Create a ListGroup component using bootstrap (provides CSS classes for styling applications)
    • Delete Vite-generated index.css and clear App.css
npm i bootstrap@5.2.3
  • In main.tsx, import bootsrap
import 'bootstrap/dist/css/bootstrap.css'
  • Create folder components in src and add ListGroup.tsx
    • Add it to App.tsx

Tip: Shortcut to find file

ctrl + p

  • Create ListGroup using bootstrap
    • change class to className (highlight each class text by pressing ctrl + d)
    • To return an h1 element along with the list element, Command Palette wrap with abbreviation div
      • But this adds an extra element div to the DOM, so a better way is to use fragments
      • Even better is to use empty elements <> and </> to avoid importing Fragments
import { Fragment } from "react";
 
function ListGroup() {
  // return <h1>List Group</h1>;
  return (
    <Fragment>
      <h1>List</h1>
      <ul className="list-group">
        <li className="list-group-item">An item</li>
        <li className="list-group-item">A second item</li>
        <li className="list-group-item">A third item</li>
        <li className="list-group-item">A fourth item</li>
        <li className="list-group-item">And a fifth one</li>
      </ul>
    </Fragment>
  );
}
 
export default ListGroup;
 
  • When rendering a list of items using map, should give each item a unique key
function ListGroup() {
  const items = ["New York", "San Francisco", "Tokyo", "London", "Paris"];
  return (
    <>
      <h1>List</h1>
      <ul className="list-group">
        {items.map((item) => (
          <li key={item} className="list-group-item">
            {item}
          </li>
        ))}
      </ul>
    </>
  );
}
 
export default ListGroup;

picture 1


11/27/24