Hands-on Practice

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.

media component UI
  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.

GYHD

Vite + React Project Creation

Step 1: Set Up the React App

  1. go to vite.dev site and click get started (https://vite.dev/guide/).

    1. Vite requires Node.js version 18+ or 20+.

    2. 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.

Last updated