πŸŽ‰ Use coupon LEARN40 and get 40% OFF on all courses! Limited time β€” don’t miss out! - Use code:

LEANR40

Setting Up a React Project

30 min read 42 views 0 comments
Setting Up a React Project
Step 1: Setting Up a React Project

Step 1: Setting Up a React Project

A beginner-friendly guide assuming only basic computer knowledge


Understanding What React Is

React is a JavaScript library used to build modern websites and web applications. Popular platforms such as Instagram, Facebook, and Netflix use React.

React helps developers build websites that are:

  • Fast and responsive
  • Easy to manage
  • Reusable (write once, use many times)
React runs on your computer using Node.js.

What You Need Before Installing React

Before starting, make sure you have the following three things:

Tool Purpose
Node.js Required to run React
Code Editor Used to write React code
Web Browser Used to view the output

Step 1.1: Install Node.js

Node.js allows JavaScript to run on your computer. React cannot function without it.

  1. Open Google
  2. Search for Node.js
  3. Open the official website
  4. Download the LTS version
  5. Install by clicking Next until Finish

To confirm installation:

node -v
            
If you see a version number, Node.js is installed correctly.

Step 1.2: Install a Code Editor (VS Code)

Visual Studio Code is where you will write your React code. Think of it as a notebook for coding.

  1. Search for Visual Studio Code
  2. Download and install it
  3. Open VS Code after installation

Step 1.3: Create a Folder for Your React App

  1. Go to your Desktop
  2. Create a new folder
  3. Name it react-learning

Step 1.4: Open the Folder in VS Code

  1. Open VS Code
  2. Click File β†’ Open Folder
  3. Select the react-learning folder

Step 1.5: Create Your First React App

React provides a ready-made project structure to help you start quickly.

In VS Code:

  • Open the Terminal (Ctrl + J)
  • Run the command below
npx create-react-app my-first-react-app
            

React will automatically download all required files. This process may take 2–5 minutes.

Step 1.6: Run the React App

After the installation completes, run the following commands:

cd my-first-react-app
npm start
            
Your browser will open automatically, showing a spinning React logo. Your first React app is now running.

Basic Folder Structure

my-first-react-app
 β”œβ”€β”€ src            (main code)
 β”œβ”€β”€ public         (HTML files)
 β”œβ”€β”€ node_modules   (React libraries)
 └── package.json
            

Do not worry about these folders now. You will learn them step by step.

What You Have Completed

  • Installed Node.js
  • Installed Visual Studio Code
  • Created a React application
  • Successfully ran the React app
Stop here before moving ahead. Confirm that you saw the React logo running in your browser.

Step 2: Understanding React Project Structure

A very important step before writing any React code


Think of a React project like a school bag. πŸŽ’ Each folder and file has a specific purpose, and understanding this structure will make learning React much easier.

Step 2.1: Open Your Project

  1. Open Visual Studio Code
  2. Open the folder named my-first-react-app
You will see many files at first. Do not panic β€” this is normal.

Step 2.2: Most Important Folders (Beginner View)

πŸ“ src Folder (Most Important)
  • This is where you write React code
  • Nearly 90% of your work happens here
πŸ“ public Folder
  • Contains the main HTML file
  • The browser reads this folder first
πŸ“ node_modules Folder
  • Contains React libraries
  • Never modify this folder

Step 2.3: Important Files Explained Simply

public/index.html

This is the only HTML file in a React project. React runs entirely inside this file.

Inside this file, you will find:

<div id="root"></div>
            
React displays everything inside this root div.
src/index.js

This file is the entry point of your React application. It tells React where and how to display the app.

ReactDOM.createRoot(document.getElementById('root')).render(
  <App />
);
            

This means:

  • Find the root div
  • Render the <App /> component inside it
src/App.js ⭐⭐

This is the main React component. It controls what appears on the screen.

function App() {
  return (
    <div>
      <h1>Hello React</h1>
    </div>
  );
}

export default App;
            
This looks like HTML, but it is actually JSX.

Step 2.4: Make Your First Change

Edit the App.js file and replace the code with:

function App() {
  return (
    <div>
      <h1>Hello, I am learning React!</h1>
      <p>This is my first React app.</p>
    </div>
  );
}

export default App;
            

Save the file. The browser will update automatically.

You changed the website without refreshing the browser. This feature is called Hot Reloading.

Important React Rules for Beginners

  1. React components must start with a capital letter
  2. The return statement defines what appears on screen
  3. JSX looks like HTML but is actually JavaScript

What You Have Learned

  • React project folder structure
  • The role of index.html and App.js
  • Basic JSX concepts
  • How to make your first React change

Step 3: Understanding React Components

The core concept of React explained in a beginner-friendly way


React is built entirely around components. You can think of components like LEGO blocks 🧱 β€” small pieces that combine together to form a complete website.

Step 3.1: What Is a Component?

A component is a small, reusable part of a website. Each component is independent and focuses on a specific task.

Common real-life examples of components include:

  • Header
  • Button
  • Footer
  • Login form

Step 3.2: Create Your First Component

Follow these steps to manually create a component:

  1. Open the src folder
  2. Create a new file named Student.js

Step 3.3: Write the Component Code

Open Student.js and add the following code:

function Student() {
  return (
    <div>
      <h2>Student Name: Ali</h2>
      <p>Class: 10</p>
    </div>
  );
}

export default Student;
            

Explanation:

  • function Student() defines the component name
  • return() controls what appears on the screen
  • export default allows the component to be reused

Step 3.4: Use the Component Inside App.js

Open App.js and update it as shown below:

import Student from "./Student";

function App() {
  return (
    <div>
      <h1>Welcome to React Class</h1>
      <Student />
    </div>
  );
}

export default App;
            

Step 3.5: What Just Happened?

Code Meaning
import Student Brings the component into App.js
<Student /> Displays the component
Reusable Can be used multiple times

Try rendering the component multiple times:

<Student />
<Student />
<Student />
            

You will see the same component displayed three times on the screen.

Step 3.6: Important Component Rules

  • Component names must start with a capital letter
  • One component per file is considered good practice
  • A component cannot return multiple elements directly

Incorrect example:

return (
  <h1>Hello</h1>
  <p>Hi</p>
);
            

Correct example:

return (
  <div>
    <h1>Hello</h1>
    <p>Hi</p>
  </div>
);
            
You have successfully created and used your own React component.

What You Have Learned

  • What React components are
  • How to create a component
  • How to reuse a component
  • Import and export basics
Stop here before moving forward. Confirm that the Student component appears on the screen and that you understand why components are used.

Step 4: JSX (JavaScript + HTML)

Understanding the heart of React user interfaces


JSX is the core building block of React user interfaces. It allows you to write HTML-like code directly inside JavaScript.

Step 4.1: What Is JSX?

JSX stands for JavaScript XML. It looks like HTML, but it is actually JavaScript syntax understood by React.

<h1>Hello</h1>
            
This is not HTML. It is JSX that React converts into JavaScript.

Step 4.2: Why JSX Is Needed

Writing React without JSX is possible, but it becomes difficult to read and maintain. JSX makes code clearer and more expressive.

  • Easier to read and understand
  • Looks similar to HTML
  • Speeds up development

Step 4.3: Important JSX Rules

1. Only One Parent Element Is Allowed

Incorrect:

return (
  <h1>Hello</h1>
  <p>React</p>
);
            

Correct:

return (
  <div>
    <h1>Hello</h1>
    <p>React</p>
  </div>
);
            
2. Use className Instead of class

Incorrect:

<div class="box">
            

Correct:

<div className="box">
            
3. JSX Expressions Use Curly Braces {}

Curly braces allow you to insert JavaScript values inside JSX.

const name = "Ali";

<h1>Hello {name}</h1>
            

Step 4.4: Practice JSX (Hands-on)

Open Student.js and update the component as shown below:

function Student() {
  const name = "Ali";
  const className = 10;

  return (
    <div>
      <h2>Student Name: {name}</h2>
      <p>Class: {className}</p>
    </div>
  );
}

export default Student;
            
Save the file and notice that the browser updates automatically.

Step 4.5: JSX with Simple Logic

JSX allows simple JavaScript logic inside curly braces.

const marks = 85;

<p>Result: {marks > 35 ? "Pass" : "Fail"}</p>
            

This uses a conditional (ternary) operator to display dynamic content.

Step 4.6: JSX Self-Closing Tags

Incorrect:

<img></img>
            

Correct:

<img />
            
You are now combining JavaScript logic with user interface code.

What You Have Learned

  • What JSX is and why it is used
  • Important JSX rules
  • Using variables inside JSX
  • Applying simple logic in JSX
Stop here before moving forward. Confirm that variables display correctly in the browser and that you understand how curly braces work in JSX.

Step 5: Props (Passing Data Between Components)

Learn how components communicate with each other in React


In React, props (short for properties) are used to pass data from one component to another.

Props allow you to make components reusable with different data.

Step 5.1: Why Props Are Needed

Think of components as people in a classroom:

  • App = Teacher πŸ‘¨β€πŸ«
  • Student = Student πŸ‘¨β€πŸŽ“

The teacher provides information, and the student receives it. In React, the parent component sends data to the child component using props.

Step 5.2: Passing Props from App.js

Open App.js and update it as shown below:

import Student from "./Student";

function App() {
  return (
    <div>
      <h1>Student Details</h1>

      <Student name="Ali" className={10} />
      <Student name="Sara" className={9} />
      <Student name="Ahmed" className={10} />
    </div>
  );
}

export default App;
            

In this example, name and className are props.

Step 5.3: Receiving Props in Student.js

Open Student.js and modify it as shown below:

function Student(props) {
  return (
    <div>
      <h2>Student Name: {props.name}</h2>
      <p>Class: {props.className}</p>
    </div>
  );
}

export default Student;
            

Step 5.4: What Just Happened?

Part Meaning
props Object that holds all passed data
props.name Access the student name
<Student /> Send data to the component

Step 5.5: Props Are Read-Only

Props cannot be changed inside the child component.

props.name = "New Name"; // ❌ Not allowed
            
Props are immutable and must not be modified by the child component.

Step 5.6: Cleaner Way Using Destructuring

A cleaner and more readable way to access props is by destructuring.

function Student({ name, className }) {
  return (
    <div>
      <h2>Student Name: {name}</h2>
      <p>Class: {className}</p>
    </div>
  );
}

export default Student;
            
The same component now displays different data using props.

What You Have Learned

  • What props are and why they are used
  • How to pass props from a parent component
  • How to receive props in a child component
  • Why props make components reusable
Stop here before moving to the next step. Confirm that all three students display correctly and that you understand how data flows from App to Student.

Step 6: State (Dynamic Data)

Learn how React handles dynamic, changeable data inside components


In React, props are fixed data passed from a parent component, while state is changeable data managed within a component.

Step 6.1: What Is State?

State is data that can change over time. When state changes, the screen updates automatically. Examples include:

  • Counter values
  • Button clicks
  • Form input text

Step 6.2: First State Using useState

React provides a special hook called useState for managing state.

Step 6.3: Create Counter Component

Create a new file in src folder: Counter.js

Step 6.4: Write Counter Code

import { useState } from "react";

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

  return (
    <div>
      <h2>Count: {count}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

export default Counter;
            

Step 6.5: Understand Each Line

Code Meaning
useState(0) Initial value set to 0
count Current value of state
setCount Function used to update state
onClick Button click event triggers state change

Step 6.6: Use Counter in App.js

import Student from "./Student";
import Counter from "./Counter";

function App() {
  return (
    <div>
      <h1>React State Example</h1>

      <Counter />

      <Student name="Ali" className={10} />
    </div>
  );
}

export default App;
            

Step 6.7: Observe the Magic 🎩

Click the "Increase" button. The number updates automatically without refreshing the page. This is the power of React state.

Step 6.8: Important State Rules

  • Never modify state directly:
count = count + 1; // ❌ Wrong
            
  • Always use the state setter function:
setCount(count + 1); // βœ… Correct
            
You have successfully created an interactive React app using state.

What You Have Learned

  • What state is and why it is needed
  • How to use the useState hook
  • How the UI updates automatically when state changes
  • Event handling in React components
Stop here before moving to the next topic. Confirm that the counter increases correctly and that you understand why setCount is required.

Step 7: Handling Events in React

Learn how to respond to user actions like clicks and typing


In React, events are user actions such as clicking a button, typing in an input box, or hovering over elements.

Step 7.1: What Are Events? (Real Life Example)

Action React Event
Click button onClick
Type in input onChange
Hover mouse onMouseOver

React events are similar to JavaScript events but use camelCase syntax.

Step 7.2: Simple Button Click Event

Open Counter.js and update the code:

import { useState } from "react";

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

  function increaseCount() {
    setCount(count + 1);
  }

  return (
    <div>
      <h2>Count: {count}</h2>

      <button onClick={increaseCount}>
        Increase
      </button>
    </div>
  );
}

export default Counter;
            
Cleaner and easier to read than inline functions.

Step 7.3: Event Rules

Incorrect:

onClick={increaseCount()}
            

Correct:

onClick={increaseCount}
            

React calls the function only when the event occurs (e.g., button click).

Step 7.4: Handling Input (Text Box)

Create a new file in src folder: InputExample.js

Step 7.5: Input with State

import { useState } from "react";

function InputExample() {
  const [name, setName] = useState("");

  function handleChange(event) {
    setName(event.target.value);
  }

  return (
    <div>
      <h2>Your Name: {name}</h2>

      <input
        type="text"
        placeholder="Enter name"
        onChange={handleChange}
      />
    </div>
  );
}

export default InputExample;
            

Step 7.6: Use Input Component

import Counter from "./Counter";
import InputExample from "./InputExample";

function App() {
  return (
    <div>
      <h1>React Events</h1>

      <Counter />
      <InputExample />
    </div>
  );
}

export default App;
            

Step 7.7: Observe the Result πŸ‘€

Type in the input box and see the text update live. No page refresh is needed β€” this is React in action.

Step 7.8: Event Object Explained Simply

Part Meaning
event Information about the action
target The input element that triggered the event
value The text typed in the input
You have successfully handled click and input events in React.

What You Have Learned

  • What React events are
  • How to use onClick for buttons
  • How to use onChange for input boxes
  • How to use the event object
Stop here before moving forward. Confirm that typing in the input shows live text and that you understand how events work.

Step 8: React Hooks, useState, useEffect, and Forms

Learn about Hooks, dynamic state, lifecycle methods, and handling forms


Step 8.1: What Are Hooks?

Hooks are special functions in React that let functional components use state, lifecycle, and other features previously only available in class components.

  • useState β†’ Manage state
  • useEffect β†’ Run code after render / side-effects

Step 8.2: Recap useState

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

// Multiple states:
const [name, setName] = useState("");
const [age, setAge] = useState(15);
            

Each piece of data can have its own state.

Step 8.3: useEffect (Lifecycle Hook)

useEffect runs code automatically after render, or when specified state/data changes.

Step 8.4: Syntax Example

import { useState, useEffect } from "react";

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

  useEffect(() => {
    console.log("Component rendered or count changed!");
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}
            

Step 8.5: How useEffect Works

Dependency Array When useEffect Runs
[] Once, after first render
[count] Whenever count changes
No array After every render

Step 8.6: Real useEffect Example (Timer)

import { useState, useEffect } from "react";

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    return () => clearInterval(interval); // cleanup
  }, []);

  return (
    <div>
      <h2>Seconds: {seconds}</h2>
    </div>
  );
}

export default Timer;
            

Seconds will increase automatically. Cleanup stops timer on unmount.

Step 8.7: Forms in React

Forms = inputs + buttons + data handling.

Step 8.7.1: Simple Form Example

import { useState } from "react";

function FormExample() {
  const [name, setName] = useState("");
  const [submittedName, setSubmittedName] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    setSubmittedName(name);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Enter your name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <button type="submit">Submit</button>
      </form>

      {submittedName && <h3>Hello, {submittedName}!</h3>}
    </div>
  );
}

export default FormExample;
            

Step 8.7.2: Explanation

Part Meaning
value={name} Input reflects state
onChange Update state when typing
event.preventDefault() Stop page refresh on submit
setSubmittedName(name) Save submitted value
{'{submittedName && ...}'} Conditional rendering

Step 8.8: Handling Multiple Inputs

const [form, setForm] = useState({ name: "", age: "" });

function handleChange(e) {
  const { name, value } = e.target;
  setForm({ ...form, [name]: value });
}

<input type="text" name="name" value={form.name} onChange={handleChange} />
<input type="number" name="age" value={form.age} onChange={handleChange} />
            

One useState can manage multiple form fields.

Step 8.9: Key Takeaways

  • useState β†’ store dynamic data
  • useEffect β†’ run code after render / data change
  • Forms β†’ value + onChange + onSubmit
  • Multiple inputs β†’ use object in state

Step 8.10: Combined Example

import { useState, useEffect } from "react";

function App() {
  const [name, setName] = useState("");
  const [submittedName, setSubmittedName] = useState("");

  useEffect(() => {
    if(submittedName) {
      console.log(`Form submitted: ${submittedName}`);
    }
  }, [submittedName]);

  function handleSubmit(e) {
    e.preventDefault();
    setSubmittedName(name);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Enter name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <button type="submit">Submit</button>
      </form>

      {submittedName && <h3>Hello, {submittedName}!</h3>}
    </div>
  );
}

export default App;
            
Live demo combining useState, useEffect, and form handling.

What You Have Learned in Step 8

  • Hooks: useState & useEffect
  • State updates automatically
  • Lifecycle with useEffect
  • Simple form handling
  • Handling multiple inputs with a single state object
  • Conditional rendering
Stop here before moving forward. Confirm that the form submits and shows a message correctly, and that you understand how useEffect reacts to state changes.

Step 9: React Router β€” Navigation and Dynamic Routes

Learn how to navigate between multiple pages and use dynamic routes in React


Step 9.1: What is React Router?

By default, React apps are single-page applications. React Router allows multiple pages without refreshing the browser.

  • / β†’ Home page
  • /about β†’ About page
  • /contact β†’ Contact page

Analogy: Switching tabs in a notebook instead of opening a new notebook.

Step 9.2: Installing React Router

npm install react-router-dom
            

This library helps handle routing in React web apps.

Step 9.3: Create Basic Components

function Home() { return <h1>Home Page</h1>; }
export default Home;

function About() { return <h1>About Page</h1>; }
export default About;

function Contact() { return <h1>Contact Page</h1>; }
export default Contact;
            

Step 9.4: Setup Router in App.js

import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";

function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link> | 
        <Link to="/about">About</Link> | 
        <Link to="/contact">Contact</Link>
      </nav>

      <Routes>
        <Route path="/" element=<Home /> />
        <Route path="/about" element=<About /> />
        <Route path="/contact" element=<Contact /> />
      </Routes>
    </Router>
  );
}

export default App;
            

Step 9.5: Explanation

Part Meaning
<Router> Wraps the entire app
<Routes> Container for all routes
<Route path="..." element={...} /> Define page URL and component
<Link to="..."> Navigation link without page reload

Step 9.6: Dynamic Routes

Sometimes the URL changes based on data, e.g., /user/:id

import { useParams } from "react-router-dom";

function User() {
  const { id } = useParams();
  return <h1>User ID: {id}</h1>;
}

export default User;
            

Step 9.7: Add Dynamic Route in App.js

<Route path="/user/:id" element=<User /> />
            

Navigate to /user/101 β†’ shows User ID: 101

Step 9.8: Programmatic Navigation

import { useNavigate } from "react-router-dom";

function Home() {
  const navigate = useNavigate();

  return (
    <div>
      <h1>Home Page</h1>
      <button onClick={() => navigate("/about")}>Go to About</button>
    </div>
  );
}

export default Home;
            

Clicking the button navigates without page refresh.

Step 9.9: Key Points

  • Wrap the app with <Router>
  • Use <Routes> to define <Route>s
  • Use <Link> instead of <a> for navigation
  • Dynamic routes β†’ /something/:param
  • useParams() β†’ Access URL parameters
  • useNavigate() β†’ Navigate programmatically
Multi-page React app with dynamic URLs and navigation without reload βœ…

What You Have Learned

  • Installing React Router
  • Creating multiple pages
  • Navigation with <Link>
  • Dynamic routes using :id
  • Accessing route params with useParams()
  • Programmatic navigation with useNavigate()
Stop here before moving next. Confirm that you can navigate between pages using Links, and understand dynamic route /user/:id.

Comments (0)

No comments yet

Be the first to share your thoughts!

Leave a Comment

Your email address will not be published.