Site icon Random Expert

How to Set Up Your First React Project: A Step-by-Step Guide

Your First React Project: Setup, Structure, and Hello World

Your First React Project: Setup, Structure, and Hello World

Alright, welcome back to “The React Alchemist: React Essentials” series! In our last session, we talked a lot about *why* React exists and what makes it special. Now, it’s time to get our hands dirty. We’re going to jump straight into the code, setting up our very first React projects. Don’t worry if it feels a bit fast; we’ll break down every step. The goal here is to get something running, see how it works, and then we can dive into the nitty-gritty details later, you know?

Learning Objectives

By the end of this article, you should be able to:

  • Set up your development environment for React.
  • Create new React projects using both `create-react-app` and Vite.
  • Understand the basic file structure of a fresh React project.
  • Run your React application in development mode.
  • Clean up a new React project to display a simple “Hello World” message.
  • Grasp the roles of the `react` and `react-dom` libraries.
  • Understand the purpose of the `build` process in React.

Prerequisites

Just a quick reminder, before we really get going, make sure you’re comfortable with:

  • HTML & CSS Basics: You’ll be working with web elements, so knowing how they’re structured and styled is pretty essential.
  • JavaScript Mastery: This is, like, super important. We’re not just talking about basic syntax. You should have a solid understanding of JavaScript’s execution context, how functions work, and especially how to manipulate the DOM. If you’ve been through our JavaScript series, you’re probably in a great spot!

Tools for the Alchemist’s Lab: Setting Up Your Environment

Building React applications doesn’t require anything super fancy. Web development, generally speaking, isn’t platform-dependent. Whether you’re on Windows, macOS, or Linux, the process is largely the same. You’ll need just two main things:

  1. A Code Editor: I’m personally a big fan of VS Code, and many developers use it. But hey, if you prefer Vim, Sublime Text, or something else, that’s totally fine! The code will work just the same.
  2. Node.js: This is crucial. Normally, JavaScript runs only in the browser. Node.js, however, gives us a JavaScript runtime environment outside the browser. Think of it like a Python interpreter for JavaScript. When you install Node.js, you also get `npm` (Node Package Manager) and `npx` (Node Package Executor), which we’ll use a lot.

    To check if Node.js is installed and see its version, open your terminal or command prompt and type:

    node -v

    My version might be different from yours, but any recent LTS (Long Term Support) or current version should be perfectly fine. The code we write won’t be affected by minor version differences.

Navigating the Ancient Scrolls: React Documentation

Before we create our first project, it’s worth a quick note on documentation. While this series will guide you step-by-step, getting comfortable with official documentation is a superpower for any developer. React’s official documentation is now at react.dev. It’s a fantastic resource for learning, and it’s always up-to-date. We’ll be referring to it, and you should too!

The Core Elements: `react` and `react-dom`

Here’s a little secret, or maybe not so secret, about React: the core library is actually just called `react`. It contains all the fundamental concepts for building UIs. But then, there are “attachments” that let React work in different environments:

  • `react-dom`: This is the library you use when you want to build web applications that run in a browser. It’s the “glue” that connects your React components to the actual HTML DOM.
  • `react-native`: If you’re building mobile applications (iOS or Android) with React, you’d use `react-native`. It takes your React knowledge and applies it to native mobile UI components.

So, when we build for the web, we’ll always use both `react` and `react-dom` together. It’s like having the core engine and then a specific adapter for the kind of vehicle you want to build.

Exercise 2.1: Tool Check

Open your terminal and check your Node.js version. If it’s not installed, go ahead and install it from nodejs.org. What version did you find?

Solution: The specific version will vary, but you should see something like `v18.17.0` or `v20.11.0`. As long as it’s a relatively recent version, you’re good to go!

Forging Your First Artifact: Creating a React Project

There are a couple of popular ways to kickstart a React project. We’ll explore two of them: `create-react-app` and Vite. Understanding both is pretty useful, even if one is a bit more common these days.

Method 1: Using `create-react-app` (The Traditional Way)

The `create-react-app` utility was, for a long time, the go-to tool for setting up React projects. It’s a command-line tool that sets up a new React project with a sensible default configuration.

Open your terminal, navigate to where you want to create your project, and run:

npx create-react-app 01-basic-react

Now, you might notice this takes a bit of time, even on a fast machine. `create-react-app` installs a lot of dependencies, some of which you might not even need initially. This can result in a larger project bundle size. While it’s good to know this method, it’s not always the fastest or most lightweight option anymore.

Exploring the `create-react-app` Project Structure

Once the installation finishes, navigate into your new project folder:

cd 01-basic-react

Now, let’s peek inside. The first file you should always check in any Node.js project is `package.json`. It’s like the manifest for your project, listing its name, version, and, most importantly, its dependencies and scripts.

{
  "name": "01-basic-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

See those `dependencies`? You’ll find `react` and `react-dom` there, as expected. But also, a bunch of testing libraries and `react-scripts`. These `scripts` are super important; they define commands like `start` (for development), `build` (for production), and `test`.

Running and Building Your `create-react-app` Project

To start your development server and see your project in the browser, run:

npm start

This will usually open your browser to `localhost:3000` (or another available port) and show you the default React spinning logo. If you right-click and view the page source, you’ll notice something interesting: there’s barely any HTML! Just a `

`. This is because React dynamically injects your UI into that root div.

When you’re ready to deploy your application, you’ll create a production-ready version using the `build` script:

npm run build

This command creates a `build` folder. Inside, you’ll find optimized HTML, CSS, and JavaScript files. This `build` folder is what you actually deploy to your web server, not your source code. It’s how React compiles your JSX and components into something browsers can understand efficiently.

Cleaning Up `create-react-app` for “Hello World”

The default `create-react-app` project comes with a lot of boilerplate code, which can be overwhelming. Let’s simplify it to just a “Hello World” message. This helps you see the bare minimum required.

In your project’s `src` folder, you can safely delete the following files (if they exist):

  • `setupTests.js`
  • `reportWebVitals.js`
  • `logo.svg`
  • `App.test.js`
  • `App.css` (or you can keep it if you want to add some basic styling later)
  • `index.css` (you can keep this for global styles, but for now, let’s simplify)

After deleting, your `src` folder should primarily contain `index.js` and `App.js` (and maybe `index.css` if you kept it). Now, let’s modify `index.js` and `App.js`.

Modify `src/index.js`:

Remove any imports related to the files you deleted (like `reportWebVitals`). Your `index.js` should look something like this:


import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css'; // Keep if you kept index.css, otherwise remove
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  
    
  
);
            

Modify `src/App.js`:

This is where your main component lives. We’ll strip it down to a simple function that returns an `h1` tag.


import React from 'react';
// import './App.css'; // Remove if you deleted App.css

function App() {
  return (
    <div>
      <h1>The React Alchemist: Hello World!</h1>
    </div>
  );
}

export default App;
            

Now, run `npm start` again. You should see a much cleaner page displaying “The React Alchemist: Hello World!” This is the absolute minimum to get React rendering.

Exercise 2.2: Clean Up Challenge

Follow the steps above to clean up your `create-react-app` project. After making the changes, what does your `App.js` file look like? Can you explain why we removed the `logo.svg` import?

Solution: Your `App.js` should resemble the simplified version provided above, with minimal imports and a basic `h1` return. We removed `logo.svg` because we deleted the actual SVG file and no longer needed to display the React logo. It’s good practice to remove unused imports and assets to keep your project lean.

Method 2: Using Vite (The Modern, Faster Way)

Vite has become incredibly popular for its speed and lightweight nature. It’s a build tool that offers a much faster development experience compared to `create-react-app`.

First, make sure you’re outside your `01-basic-react` folder (you can use `cd ..` to go up one directory in the terminal). Then, run the following command:

npm create vite@latest

Vite will then ask you a few questions:

  • Project name: Type `02-vite-react` (or whatever you like).
  • Select a framework: Use your arrow keys to select `React` and press Enter.
  • Select a variant: Choose `JavaScript` (or `TypeScript` if you’re feeling adventurous, but for this series, we’ll stick to JavaScript for simplicity).

Vite will quickly create your project. You’ll notice it’s much faster than `create-react-app`!

Installing Dependencies for Vite

Unlike `create-react-app`, Vite doesn’t automatically install all Node modules. You’ll need to do that manually:

cd 02-vite-react
npm install

You can also use the shorthand `npm i`. This command reads the `dependencies` in your `package.json` and downloads them into a `node_modules` folder. Even with this step, Vite is typically much quicker.

Exploring the Vite Project Structure

Again, let’s look at `package.json` in your new Vite project:

{
  "name": "02-vite-react",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "@vitejs/plugin-react": "^4.0.3",
    "eslint": "^8.45.0",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.3",
    "vite": "^4.4.5"
  }
}

Notice how the `dependencies` section is much leaner, primarily just `react` and `react-dom`. Vite handles a lot of the build process more efficiently, so it doesn’t need as many direct dependencies in your project. You’ll also see `devDependencies`, which are tools used only during development and aren’t shipped to production.

Running Your Vite Project

To run your Vite project in development mode, use the `dev` script:

npm run dev

This will usually start the server on `localhost:5173` (or another port) and display the default Vite + React page.

Cleaning Up Vite for “Hello World”

Similar to `create-react-app`, Vite also generates some boilerplate. Let’s clean it up to display our simple message.

In your `src` folder (inside `02-vite-react`), you can delete:

  • `assets` folder (contains the React and Vite logos)
  • `App.css`
  • `index.css`

After deletion, your `src` folder should mostly contain `main.jsx` (or `main.js`) and `App.jsx` (or `App.js`).

Modify `src/main.jsx` (or `main.js`):

Remove any CSS imports you deleted. It should look like this:


import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
// import './index.css' // Remove if you deleted index.css

ReactDOM.createRoot(document.getElementById('root')).render(
  
    
  ,
)
            

Modify `src/App.jsx` (or `App.js`):

Strip this down to just the `h1` tag.


import React from 'react'
// import './App.css' // Remove if you deleted App.css

function App() {
  return (
    <div>
      <h1>The React Alchemist: Vite Power!</h1>
    </div>
  )
}

export default App
            

Run `npm run dev` again, and you should now see “The React Alchemist: Vite Power!” displayed cleanly.

Conclusion

Phew! That was quite a journey, wasn’t it? We’ve successfully set up our development environment and created React projects using both `create-react-app` and Vite. More importantly, we learned how to strip down those initial projects to their bare essentials, getting a simple “Hello World” to display. This might seem like a small step, but it’s a huge confidence booster, showing you that you can indeed manipulate these projects.

You’ve also gotten a glimpse into the project structure, the role of `package.json`, and how to run and build your applications. This foundational knowledge is, well, foundational!

Next Steps

Now that you know how to get a React project up and running, and how to clean it up, the next step is to truly understand what’s happening behind the scenes. In our next article, we’ll dive deeper into the execution flow of a React project, exploring how files are linked, how React renders to the DOM, and the lifecycle of a React application. It’s going to be an interesting dive into the internal workings!

Exit mobile version