Lesson 2 / 1118%

Lesson 2

Installation and First Project

18 min

Install Node.js, create a project with Vite and display your first component.

Definition

A development environmentis the set of tools needed to write, test, and run code. For React, it includesNode.js, which allows JavaScript to run outside the browser,npm, which manages libraries, a code editor, and a tool such as Vite, which makes it easier to create and run a project.

Before writing your first React component, you need to prepare your computer. This step involves installing a few essential tools and checking that they work. Once this setup is complete, you will be able to create as many React projects as you want.

In this lesson, you will install Node.js, discover the terminal, create a project with Vite, explore the generated files, and display your first message in the browser. You will also learn how to recognize and fix the most common installation errors.

What You Need to Install

To develop a React application, you need three main tools. Each has a different role, and they work together during development.

  • Node.js:allows JavaScript to run outside the browser. It also includes npm. Download the LTS version fromnodejs.org.
  • A code editor:Visual Studio Codeallows you to easily write, organize, and edit your project files.
  • A modern browser:Chrome, Firefox, or Edge allows you to display your application and test how it works.

These tools perform complementary functions. The editor is used to write code, Node.js allows you to use development tools, while the browser displays the final result. You will regularly switch between them during the exercises.

Understanding Node.js and npm

Node.js is a JavaScript runtime environment. Usually, JavaScript runs in a browser. Node.js also allows you to run it directly on your computer, especially when using development tools.

npm stands forNode Package Manager. It is a package manager that allows you to install JavaScript libraries. Thanks to npm, you do not need to manually download every file required by your React application.

For example, when you create a React project, npm can install React, React DOM, Vite, and other necessary tools. It uses the information contained in thepackage.jsonfile to identify the project's dependencies.

Why Choose the LTS Version?

The LTS version (Long Term Support) of Node.js benefits from an extended maintenance period. It is generally recommended for beginners because it prioritizes stability and security updates.

The Current version provides new features more quickly, but it has a shorter maintenance cycle. To follow this course, choose a recent LTS version compatible with the version of Vite being used.

Checking the Installation

After installing Node.js, open a terminal. On Windows, you can use PowerShell or the terminal integrated into Visual Studio Code. On macOS and Linux, use the Terminal application.

Then run the following commands to check that Node.js and npm are available:

terminal
node --version
npm --version

Each command should display a version number. For example, Node.js may display a version in the formatvXX.YY.ZZ. The exact number depends on the installed version.

If the terminal displays "command not found" or "command not recognized", close it and reopen it. If the problem persists, check that Node.js was installed correctly and is accessible from the terminal.

Screenshot of the terminal displaying the Node.js and npm versions after running both commands.

Discovering the Terminal

The terminalis a tool that allows you to communicate with your computer using text commands. In a React project, it is mainly used to create projects, install dependencies, and start the development server.

It is important to know which folder you are in before running a command. Some commands operate on the current directory. If you are in the wrong location, they may fail or modify another project.

useful commands
# Display the current directory
pwd

# Enter a folder
cd my-app

# Return to the parent directory
cd ..

# Display files (macOS/Linux)
ls

# Display files (Windows)
dir

Some commands differ depending on the operating system. For example,dirworks in Windows terminals, whilelsis commonly used on macOS and Linux. PowerShell also supports several similar commands.

Creating a Project with Vite

Vite is a tool that makes developing modern web applications easier. It allows you to quickly create a React project and provides a fast development server.

Instead of manually configuring all the files, you can use Vite to generate a ready-to-use project structure. This allows you to focus on learning React more quickly.

terminal
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

The first command creates a project namedmy-app. The--template reactparameter indicates that you want to use the React template with JavaScript.

Depending on the Vite version, a few additional questions may appear. If you need to choose a framework, selectReact. For the variant, choose JavaScriptinstead of TypeScript to follow this course.

Understanding the Four Commands

  • npm create vite@latest:generates the starting files for the React project.
  • cd my-app:enters the folder that was just created.
  • npm install:installs the dependencies declared in the project.
  • npm run dev:starts the local development server.

The first three commands are mainly used when creating the project. Later, when you want to continue working, open the project folder in your terminal and runnpm run dev.

Opening the Application in the Browser

After runningnpm run dev, Vite displays a local address in the terminal. It usually looks like this:

local address
Local: http://localhost:5173/

Open this address in your browser. You should see the Vite + React template's home page, with a logo and an interactive counter. This confirms that your project is working.

The termlocalhostrefers to your own computer. The number5173is the port used by the server. If this port is already in use, Vite may automatically choose another one. Always use the address displayed in your terminal.

Screenshot of the browser showing the Vite + React project's home page with the default counter and the local address displayed in the terminal.

Exploring the Project Structure

Now open themy-appfolder in Visual Studio Code. You will discover several files and folders generated by Vite. You do not need to understand everything immediately. To get started, focus on the most important elements.

simplified structure
my-app/
├── index.html
├── package.json
├── package-lock.json
├── node_modules/
├── public/
└── src/
    ├── main.jsx
    ├── App.jsx
    ├── App.css
    ├── index.css
    └── assets/

Thesrcfolder contains most of your application's code. This is where you will mainly work during the next lessons. The exact structure may vary slightly depending on the version of the Vite template.

  • index.html:the basic HTML page in which React displays the application.
  • package.json:describes the project, its dependencies, and the available scripts.
  • main.jsx:the entry point that initializes React.
  • App.jsx:the main component of your application.
  • index.css:contains the application's global styles.
  • public:contains static files that can be accessed directly.
  • node_modules:contains the dependencies installed by npm.
Screenshot of the VS Code file explorer showing the my-app project structure with the src folder expanded.

Understanding the package.json File

Thepackage.jsonfile contains important information about your project. In particular, it specifies its name, the libraries being used, and the commands you can run with npm.

simplified package.json example
{
  "name": "my-app",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  }
}

In this example, thescriptssection defines several commands. When you typenpm run dev, npm executes the script named dev. The other scripts allow you to prepare a production version and preview it.

Understanding the main.jsx File

Themain.jsxfile is the entry point of your React application. It tells the browser where to display the components and initializes the application's rendering.

src/main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

The first lines import the necessary elements. ThecreateRootfunction creates a React root inside the HTML element whose ID isroot. Therendermethod then displays the main component.

TheStrictModecomponent helps detect certain potential problems during development. For now, you do not need to modify this file. It is mainly used to start the application.

Your First "Hello React"

It is now time to modify your application. Open thesrc/App.jsxfile, delete its content, and replace it with the following code:

src/App.jsx
function App() {
  return <h1>Hello, React!</h1>;
}

export default App;

Save the file. The browser should display the messageHello, React!. You have just created your first React component. It is a function that returns an element to display on the page.

The<h1>syntax looks like HTML, but it is written directly in JavaScript. This is calledJSX. You will discover this syntax in more detail in the next lesson.

Modifying Your First Component

Now that your component works, try changing the displayed message. You can also add a paragraph below the heading. To return multiple elements, use a parent element or a React fragment.

src/App.jsx
function App() {
  return (
    <div>
      <h1>Welcome to my application!</h1>
      <p>I'm learning React with Vite.</p>
    </div>
  );
}

export default App;

In this example, the component returns two elements: a heading and a paragraph. They are grouped inside a<div>tag. You can freely modify their content to observe the result.

Understanding Automatic Updates

When you modify a file in your project and save it, Vite detects the change. It can automatically update the browser through a mechanism calledHot Module Replacement, or HMR.

This feature is very useful during development. You can change a heading, add a paragraph, or modify a color and quickly see the result on the screen. However, some changes may require a complete page reload.

Stopping and Restarting the Server

As long as the development server is running, the terminal remains occupied. To stop the server, return to the terminal and pressCtrl + C.

To continue working later, open the project in Visual Studio Code, then run the following command from its folder:

restart the project
cd my-app
npm run dev

Good to Know

The development server is used to test your application on your computer. It is not the same as an application published on the Internet. Later, you can use thenpm run buildcommand to generate the files intended for production.

Common Errors

  • Node.js command not found:check the Node.js installation and restart the terminal.
  • Wrong directory:make sure you run npm commands inside the project folder.
  • Missing dependencies:runnpm installto install the libraries.
  • Server stopped:restart it withnpm run dev.
  • Unsaved file:save your changes so they can take effect.
  • Syntax error:check parentheses, curly braces, and JSX tags.
  • Page unavailable:check the local address displayed by Vite in the terminal.

Learning to Read Error Messages

During development, you will sometimes encounter error messages. They may appear in the terminal, in the browser, or in the code editor. These messages often provide useful information to help you fix the problem.

Start by reading the name of the affected file and the line number when they are provided. Then check the section of code mentioned in the message. A single missing parenthesis or an improperly closed tag can prevent the application from working.

JSX error example
// Incorrect
function App() {
  return <h1>Hello React!;
}

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

In this example, the first version does not properly close the<h1>tag. The second version fixes this error. Learning to identify this type of problem is part of a developer's everyday work.

Preparing Your Workspace

To work efficiently, organize your screen so you can easily see both the code and the result. You can place Visual Studio Code on one side of the screen and the browser on the other.

Also keep the terminal accessible to check Vite's messages and verify that the server is running. This setup will allow you to modify your code and quickly observe the changes.

Exercise

Install Node.js, check the Node.js and npm versions, then create yourmy-appproject with Vite. Start the development server, open the application in your browser, and modifyApp.jsxto display your first name. Check that the page updates automatically.

Go Further

Explore the structure of your project. Remove unnecessary elements from the template, such asApp.cssor some logos from thesrc/assetsfolder. Remember to remove the corresponding imports as well. Then add a heading and a paragraph to your App component, and check that the application still works.

Key Takeaways

  • Node.jsallows you to use JavaScript tools on your computer.
  • npmis used to install and manage project dependencies.
  • Viteallows you to quickly create a React project and start a development server.
  • Thenpm create vite@latestcommand allows you to start a new project.
  • Thenpm installcommand installs dependencies.
  • The server starts withnpm run devand stops withCtrl + C.
  • Thesrcfolder contains most of the application's code.
  • TheApp.jsxfile contains the main component of your project.
  • Vite allows you to quickly observe changes made to the code.
  • Error messages provide useful information for identifying and fixing problems.