ReactJS-The Beginner Master Class
  • React In the Beginning
    • Lesson 1 - Demo: Build a Simple React App - Fast
    • Lesson 2 - HTML Review
    • Lesson 3 - CSS Review
    • Lesson 4 - Modern JavaScript (JSX) Patterns
    • Lesson 5 - Set up Dev Environment
    • Hands-on Practice
  • React Fundamentals
    • Lesson 1 - Understanding Old vs New Way of Building Web Apps - SPAs
    • Lesson 2 - Motivation for Using React as the Solution to Vanilla JS
    • Lesson 3 - What is ReactJS - How it Works
    • React Code Along from Scratch
    • Lesson 4 - Create and Run a React Project with Vite - Full Overview
    • Lesson 5 - Create Hook by State Management in React
    • Lesson 6 - React Project File and Folder Walkthrough
    • Lesson 7 - JSX and How React Treats the DOM & JSX Compilation(by Babeljs) - Overview
    • Lesson 8 - Understanding the Main Files - App.jsx and main.jsx
    • Lesson 9 - Props and One-Way Data Flow - Overview
    • Lesson 10 - Google Bookshelf App - Ver 1.0
    • Hands-on Practice I
    • Hands-on Practice II
  • React State and Styling
    • Lesson 1 - Pulling Book Data from a Different Data File
    • Lesson 2 - Overview of How State Works in React
    • Lesson 3 - RandomQuote App
    • Lesson 4 - Lifting State Up - React Pattern Overview
    • Hands-On - Simple Counter
  • Forms and Interactivity - Grocery List App
    • Lesson 1 - Setup a Simple Form and Input
    • Lesson 2 - Build Form Profile App Using Multi-input Form Data
    • Hands-on : Build a Grocery List App
  • Connecting to the Backend - Consuming APIs - UseEffect Hook
    • Lesson 1 - Connecting to the Back End - Understanding Side Effects, Hooks and useEffect - Overview
    • Lesson 2 - Fetching Data from the Backend the Right Way with useEffect Hook
    • Lesson 3 - Setting Up Loading State
    • Hands-on :Use Dependency Array and Adding Values that Control Side Effects
  • Solo Project 1
  • RESTful APIs :Build a BookSearch App -Ver 2.0
    • Lesson 1: Build and test RESTful APIs with Postman
    • Lesson 2 - BookShelf App Structure
    • Lesson 3 - Create NavBar.jsx Component
    • Lesson 4 - Create Footer Component
    • Lesson 5 - Create BookList.jsx Component
    • Lesson 6 - Create BookCard.jsx Component
    • Lesson 7 - Creating Custom Hooks - useBooks and api-client
    • Lesson 8 - Controlling Network Activities in React with AbortController
    • Lesson 9 - Show Book Details in a Modal - Working
    • Lesson 10 - Bookshelf App Summary
  • Multi-Page Applications (MPAs)
    • Build a Multi-Page React Application
    • Multi-Page React Application
    • Hands-on Practice
  • Backend Frameworks-NEXT.JS
    • Migrating from React to Next.js
    • Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development
    • Lesson 2: How to set up a new Next.js project
    • Lesson 3: How to create Layouts and Pages
    • Hands-on Practice 1
    • Hands on Practice 2
      • New Project & Folder Structure
      • File-Based Routing
      • Server vs Client Components & Router Hooks
      • Start On The Navbar
      • Navbar Links, Dropdowns & React Icons
      • Active Links & Conditional Rendering
      • Homepage Components
      • Properties Page
      • Property Card Dynamic Data
      • Home Property Listings
      • Custom Not Found & Loading Pages
  • Git and GitHubs
    • Git Installation
    • Git Commands
    • GitHub Repository
    • Hands-on Practice
  • Database in Application
    • React Supabase CRUD
    • Hands-on: Note Taking App
  • NoSQL Database
    • Installing MongoDB Community Edition
    • System Env Path Setting
    • How to use MongoDB Shell
    • How to Connect and Use Mongosh in VS Code via MongoDB Extension
    • MongoDB Guide
  • Solo Project 2
  • Deployment and Web Hosting
    • Lesson 1. React+Vite+TS+Shadcn Project
    • Lesson 2. Deploying a React Vite App to Vercel from Vercel CLI
    • Lesson 3 Connecting to GitHub Repo and Automate Deployment
  • Solo Project 3
  • Final Term Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 2 Team Project
    • Level 2 Team Project
    • Level 3 Team Project
    • Level 3 Team Project
Powered by GitBook
On this page
  • Learn to "Think in React"
  • The "Thinking in React" Process (5 Steps)
  • How to Start Developing React Apps (for Beginners)
  • Example: A Simple Counter (Illustrating "Thinking in React")
  • Implementation of a React Calculator App
  • Vite + React Project Creation
  • Step 1: Set Up the React App
  • Step 2: Create Component Files
  • Step 3: Implement Result.jsx using arrow function
  • Step 4: Implement Calculator.jsx
  1. React In the Beginning

Hands-on Practice

PreviousLesson 5 - Set up Dev EnvironmentNextReact Fundamentals

Last updated 3 months ago

Learn to "Think in React"

"Thinking in React" is a mindset and a process for approaching the development of user interfaces with the React library. It's about breaking down complex UIs into smaller, manageable, reusable components and then defining how data flows between them. This approach makes building and maintaining complex applications much easier.

The "Thinking in React" Process (5 Steps)

  1. Break the UI into a component hierarchy: Start by drawing boxes around every component (and sub-components) in your UI design. Give them descriptive names. This is your component tree.

    • Single Responsibility Principle: Each component should ideally do one thing and do it well. If a component grows too complex, break it down further.

  1. Build a static version in React: Focus on creating a working version of your UI that renders the data correctly. Don't worry about interactivity yet. This step ensures you have the correct component structure and data flow.

    • Props: Use props to pass data from parent components down to child components.

  2. Identify the minimal (but complete) representation of UI state: Determine the absolute minimum set of state variables your app needs. Avoid redundant state.

    • State: State is data that changes over time and affects the UI. Identify what data needs to change in response to user interactions or other events.

  3. Identify where your state should live: Determine which component should "own" each piece of state. This is often the common ancestor of all components that need to use or modify that state.

    • Lifting State Up: If multiple components need access to the same state, lift the state up to their nearest common ancestor component.

  4. Add inverse data flow: Implement the interactivity. This usually involves passing callback functions down through props, allowing child components to update the state in their parent components.

    • Event Handlers: Use event handlers (e.g., onClick, onChange) to trigger state updates.

How to Start Developing React Apps (for Beginners)

  1. Set up your development environment:

    • Node.js and npm (or yarn): Install Node.js, which includes npm (Node Package Manager). Yarn is an alternative package manager you can choose.

    • Create Vite+React App : This is the easiest way to start a new React project:

  2. Understand basic JavaScript (ES6+): React relies heavily on modern JavaScript features like:

    • const and let: For variable declarations.

    • Arrow functions: Concise function syntax.

    • Destructuring: Extracting values from objects and arrays.

    • Modules (import/export): Organizing code into reusable modules.

    • JSX: A syntax extension that allows you to write HTML-like code within JavaScript.

    • Learn the core React concepts:

      • Components: The building blocks of React UIs.

      • JSX: How to write HTML-like code in JavaScript.

      • Props: Passing data from parent components to child components.

      • State: Managing data within a component that can change over time.

      • Hooks: Functions that let you "hook into" React state and lifecycle features from functional components. Start with useState and useEffect.

      • Events: Handling user interactions (e.g., clicks, form submissions).

  3. Practice and iterate: The best way to learn React is by doing. Build projects, experiment, and don't be afraid to make mistakes. Learn from them and keep practicing.

Example: A Simple Counter (Illustrating "Thinking in React")

Static Layout for Counter App

// UI Layout 
--------------------------------------------------------
|                    Counter Component                 |
--------------------------------------------------------
|  [useState Hook] - Initialize 'count' as 0            |
--------------------------------------------------------
|  <div>                                                |
|    -------------------------------------------------- |
|    |  <h1>     My First React Counter App  </h1>      |  <-- Header
|    -------------------------------------------------- |
|    |  <p>      Count: {count}     </p>                |  <-- Paragraph (styled in green, font size 24px)
|    -------------------------------------------------- |
|    |    [ Increment ]     [ Decrement ]               |  <-- Buttons
|    |    (Button 1)        (Button 2)                  |  <-- Increment and Decrement Buttons
|    -------------------------------------------------- |
|  </div>                                               |
--------------------------------------------------------
  1. Component Hierarchy: One component: Counter.

  2. Static Version: Render a number (initially 0) and two buttons ("Increment" and "Decrement").

  3. Minimal State: One piece of state: count (initially 0).

  4. State Location: The Counter component owns the count state.

  5. Inverse Data Flow: Add onClick handlers to the buttons that update the count state using setState.

// Counter.jsx
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2> My First React App </h2>
         <p>Count: {count}</p>
         <button onClick={() => setCount(count + 1)}>Increment</button>
         <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

export default Counter;

Implementation of a React Calculator App

This guide provides step-by-step instructions to create a React Calculator App with functionalities to Add, Subtract, Multiply, and Divide two numbers. The project will include two main files: Calculator.jsx and Result.jsx.

Vite + React Project Creation

Step 1: Set Up the React App

    1. check whether you already installed a right version of node.js

// Bash
node -v
npm -v
  1. Open Bash/PowerShell terminal and create your working directory, ie. "react-sandbox". Change the directory to "react-sandbox" and install vite latest version.

S npm create vite@latest

Then follow the prompts!

  • Project name: react-handson-practices

  • Select a framework: > React

  • Select a variant: > JavaScript

  1. Change the directory to "react-handson-practices". And then install and run.

  • Install any necessary dependencies (optional): While this basic app doesn't require additional libraries, you can install styling libraries like Bootstrap if needed:

// cd react-handson-practices
npm install
npm install bootstrap
npm run dev
  1. Click : http://localhost:5173


Step 2: Create Component Files

  1. Navigate to the src directory and create a new folder named components.

  2. Inside the components folder, create two files:

    • Calculator.jsx

    • Result.jsx

  3. Think in React way - Layout Design(Paper work)

// Layout for a Simple Calculator
--------------------------------------
|           React Calculator         | <-----Header Section
|------------------------------------|
| Number 1: [{__________}]           | <----- Number Input section & useState
|                                    |
| Number 2: [{___________}]          |
|                                    |
| Select Operator:                   | <------- Operator Selection & useState
|   (o) Add (+)   (o) Subtract (-)   | <------- operator selection handler(+,-,*,/)
|   (o) Multiply (*)  (o) Divide (/) |
|                                    |
| Button :[calculateResult]          | <-------- Button section 
|                                    |           for onClick handler for Calculation
| Result: {result}                   | <--------- Display Result
--------------------------------------

Step 3: Implement Result.jsx using arrow function

// Result.jsx
import React from 'react';

const Result = ({ result }) => {
  return (
    <div>
      <h3>Result: {result !== null ? result : '---'}</h3>
    </div>
  );
};

export default Result;

Step 4: Implement Calculator.jsx

// Calculator.jsx
import React, { useState } from 'react';
import Result from './Result';

const Calculator = () => {
  const [num1, setNum1] = useState('');
  const [num2, setNum2] = useState('');
  const [operator, setOperator] = useState('+');
  const [result, setResult] = useState(null);

  const calculateResult = () => {
    const number1 = parseFloat(num1);
    const number2 = parseFloat(num2);
//Validity Check for inputting numbers
    if (isNaN(number1) || isNaN(number2)) {
      setResult('Invalid Input');
      return;
    }

    switch (operator) {
      case '+':
        setResult(number1 + number2);
        break;
      case '-':
        setResult(number1 - number2);
        break;
      case '*':
        setResult(number1 * number2);
        break;
      case '/':
        setResult(number2 !== 0 ? number1 / number2 : 'Cannot divide by zero');
        break;
      default:
        setResult('Invalid Operator');
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '400px', margin: 'auto' }}>
      <h2>React Calculator</h2>
      <div>
        <label>
          Number 1:
          <input
            type="number"
            value={num1}
            onChange={(e) => setNum1(e.target.value)}
          />
        </label>
      </div>
      <div>
        <label>
          Number 2:
          <input
            type="number"
            value={num2}
            onChange={(e) => setNum2(e.target.value)}
          />
        </label>
      </div>
      <div style={{ margin: '10px 0' }}>
        <div>Select Operator:</div>
        <label>
          <input
            type="radio"
            value="+"
            checked={operator === '+'}
            onChange={(e) => setOperator(e.target.value)}
          />
          Add (+)
        </label>
        <label style={{ marginLeft: '10px' }}>
          <input
            type="radio"
            value="-"
            checked={operator === '-'}
            onChange={(e) => setOperator(e.target.value)}
          />
          Subtract (-)
        </label>
        <label style={{ marginLeft: '10px' }}>
          <input
            type="radio"
            value="*"
            checked={operator === '*'}
            onChange={(e) => setOperator(e.target.value)}
          />
          Multiply (*)
        </label>
        <label style={{ marginLeft: '10px' }}>
          <input
            type="radio"
            value="/"
            checked={operator === '/'}
            onChange={(e) => setOperator(e.target.value)}
          />
          Divide (/)
        </label>
      </div>
      <button onClick={calculateResult} style={{ marginTop: '10px' }}>
        Calculate
      </button>
      <Result result={result} />
    </div>
  );
};

export default Calculator;

Step 5: Update App.jsx

Replace the contents of App.jsx with the following:

// App.jsx
import React from 'react';
import Calculator from './components/Calculator';

function App() {
  return (
    <div className="App">
      <Calculator />
    </div>
  );
}

export default App;

Step 6: Start the Application

  1. Run the app:

    npm run dev
  2. Open your browser and navigate to http://localhost:5173.


Summary of Components

  • Result Component: Displays the calculated result.

  • Calculator Component: Handles user input, operator selection, and calculation logic.

go to vite.dev site and click get started ().

Vite requires version 18+ or 20+.

https://vite.dev/guide/
Node.js
media component UI
GYHD