Installing and using React on Linux: A Step-by-Step Guide
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. Maintained by Facebook and a community of individual developers and companies, React allows developers to create reusable UI components. These components manage their own state, and can then be composed to create complex UIs. The component-based approach significantly improves code reusability and maintainability, making it a popular choice for modern web development.
This guide provides a comprehensive walkthrough of installing and using React on a Linux system, specifically targeting Ubuntu 20.04/22.04 or CentOS/RHEL 7. We’ll cover everything from setting up the necessary prerequisites to deploying a production-ready application. This article focuses on Installing and using React on Linux.
Before diving in, remember that React is a library focused on the view layer of your application. It’s frequently combined with other tools and libraries to build complete web applications. For instance, you might integrate React with a backend framework like Express.js or a state management library like Redux or Zustand.
This guide focuses on the core steps to get React running on your Linux system.
Prerequisites
Before you start, ensure the following are installed on your system:
- A Linux operating system: Ubuntu 20.04/22.04 or CentOS/RHEL 7 are recommended.
- A terminal application: Used to execute commands.
- Basic Linux command-line knowledge: Familiarity with commands like
cd
,ls
, andmkdir
.
Installing Node.js and npm
Node.js is a JavaScript runtime environment that executes JavaScript code outside of a web browser. It’s essential for running React applications and many other modern web development tools.
npm (Node Package Manager) is the default package manager for Node.js. It simplifies the installation and management of third-party libraries and dependencies.
To install Node.js and npm on Ubuntu 20.04/22.04, execute these commands:
$ sudo apt update
$ sudo apt install nodejs npm
On CentOS/RHEL 7, use the following commands:
$ sudo yum update
$ sudo yum install nodejs npm
After installation, verify the versions of Node.js and npm:
$ node --version
v18.19.0
$ npm --version
10.2.3
Note: The exact versions may differ depending on when you are reading this.
Creating a new React application
Now that Node.js and npm are installed, create a new React application using the create-react-app
tool. This command-line interface (CLI) automatically sets up a new React project with a pre-configured build pipeline and development server.
Open your terminal, navigate to the desired project directory, and run the following command:
$ npx create-react-app my-app
Replace my-app
with your project’s name.
This command creates a new directory named my-app
and initializes a basic React application within it. The application includes a development server, build scripts, and a basic file structure.
Once the command finishes, navigate into the project directory:
$ cd my-app
Running the development server
With your React application created, start the development server to view your app in action.
Execute this command:
$ npm start
This compiles your application and starts a local development server, typically on http://localhost:3000
. It also automatically opens your default web browser to this address.
You should see a default React page displaying "Edit src/App.js
and save to reload." This is the default React application generated by create-react-app
.
As you modify your application’s source files, the development server automatically detects these changes and reloads the application in the browser, facilitating rapid iteration during development.
Building the application for production
When you’re ready to deploy your React application, you need to build a production-ready version.
Run the following command:
$ npm run build
This command compiles your application and outputs a static version in the build
directory of your project.
The build
directory contains all the necessary files to serve your application on a web server:
index.html
: The main HTML file for your application.static
: A directory containing JavaScript, CSS, and other assets.manifest.json
: A file containing metadata about your application.
Serving the application with a web server
Now that you have a production-ready version, serve it using a web server.
While many web servers can serve your React application, we’ll use the serve
package from npm for this guide.
Install the serve
package globally:
$ npm install -g serve
The -g
flag installs the package globally, allowing you to use the serve
command from anywhere on your system.
Once installed, start the web server by running this command in your project’s root directory:
$ serve -s build
The -s
flag specifies the directory to serve, in this case, the build
directory.
This starts a web server on http://localhost:5000
by default. Access your application by navigating to this address in your web browser.
To serve your application on a different port, use the -l
flag:
$ serve -s build -l 8080
This starts the web server on http://localhost:8080
.
Note that serve
is a basic web server for static files and may not be suitable for a production environment. For a more robust solution, consider using dedicated web servers like Apache or Nginx.
Conclusion
This guide covered the fundamentals of installing and using React on a Linux system using Ubuntu 20.04/22.04 or CentOS/RHEL 7. We covered installing Node.js and npm, creating a new React application, running the development server, building for production, and serving the application.
Further exploration of advanced topics like state management, routing, and testing is encouraged. This guide provides a strong foundation for starting React development on your Linux system.
Alternative Solutions:
While create-react-app
is a convenient way to get started with React, it’s not the only option. It can become less desirable as projects grow and require more customization. Here are two alternative approaches to setting up a React project on Linux:
1. Using Vite:
Vite is a build tool that aims to provide a faster and leaner development experience for modern web projects. It uses native ES modules and leverages browser caching during development, resulting in significantly faster cold start times and hot module replacement (HMR).
Explanation:
Instead of bundling the entire application during development like create-react-app
, Vite serves individual modules as the browser requests them. This on-demand compilation drastically reduces the time it takes to start the development server and update the application when changes are made.
Steps:
-
Create a Project Directory: Create an empty directory for your project and navigate into it using the command line.
-
Initialize a Vite Project: Use npm or yarn to initialize a new Vite project with the React template:
npm create vite@latest my-vite-app --template react cd my-vite-app
Or, using yarn:
yarn create vite my-vite-app --template react cd my-vite-app
-
Install Dependencies: Install the necessary dependencies:
npm install
Or, using yarn:
yarn install
-
Run the Development Server: Start the Vite development server:
npm run dev
Or, using yarn:
yarn dev
-
Build for Production: Build the application for production:
npm run build
Or, using yarn:
yarn build
The built files will be located in the
dist
directory.
2. Manual Setup with Webpack and Babel:
For maximum control and customization, you can set up a React project manually using Webpack as a module bundler and Babel to transpile JSX and modern JavaScript syntax.
Explanation:
This approach requires a deeper understanding of the underlying build process but provides complete flexibility to configure the project according to your specific needs. It’s particularly useful for projects with complex requirements or when you need to optimize the build process for performance.
Steps:
-
Create Project Directory and Initialize npm: Create a new project directory and initialize npm:
mkdir my-webpack-react-app cd my-webpack-react-app npm init -y
-
Install Dependencies: Install the necessary dependencies:
npm install react react-dom webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env @babel/preset-react html-webpack-plugin --save-dev
-
Create Source Files: Create the necessary source files:
src/index.js
: The entry point of your application.src/App.js
: A basic React component.public/index.html
: The HTML template.
-
Configure Webpack: Create a
webpack.config.js
file in the root directory and configure Webpack:const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, devServer: { static: path.resolve(__dirname, 'dist'), port: 8080, }, module: { rules: [ { test: /.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'], }, }, }, ], }, plugins: [new HtmlWebpackPlugin({ template: './public/index.html' })], };
-
Configure Babel: Create a
.babelrc
file in the root directory and configure Babel:{ "presets": ["@babel/preset-env", "@babel/preset-react"] }
-
Update
package.json
: Add scripts to run the development server and build the application:"scripts": { "start": "webpack serve --mode development", "build": "webpack --mode production" }
-
Example source code:
src/index.js:
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> );
src/App.js:
import React from 'react'; function App() { return ( <div> <h1>Hello, React!</h1> </div> ); } export default App;
public/index.html:
<!DOCTYPE html> <html> <head> <title>React App</title> </head> <body> <div id="root"></div> <script src="bundle.js"></script> </body> </html>
-
Run the Development Server: Start the Webpack development server:
npm start
-
Build for Production: Build the application for production:
npm run build
The built files will be located in the
dist
directory.
These alternative methods offer different levels of control and complexity, allowing you to choose the approach that best suits your project’s requirements.