Getting Started with ReactJS: Building a Simple React App with a Node.js Backend
Vassilis Koulianos
Posted on August 17, 2024
Getting Started with ReactJS: Building a Simple React App with a Node.js Backend
If you’re new to web development and want to dip your toes into creating modern web applications, ReactJS and Node.js are excellent technologies to start with. In this tutorial, we’ll guide you through creating a basic React app from scratch and connecting it to a Node.js backend. This step-by-step guide is tailored for absolute beginners, so don't worry if you're unfamiliar with some of the concepts—I'll explain everything as we go.
Step 1: Setting Up Your Development Environment
Before we start coding, you’ll need to have a few tools installed on your computer:
- Node.js and npm: Node.js is a runtime environment that lets you execute JavaScript on your server, and npm (Node Package Manager) helps you install and manage libraries. You can download them both from nodejs.org.
- A Code Editor: I recommend using Visual Studio Code, but any text editor will work.
Once you have Node.js installed, you can check the versions to confirm:
node -v
npm -v
Step 2: Creating the React App
React provides a tool called create-react-app
that simplifies the setup process. This tool creates a new React project with all the necessary configurations.
- Open your terminal and navigate to the directory where you want to create your project.
- Run the following command to create a new React app:
npx create-react-app my-react-app
This command will set up a new directory called my-react-app
with a basic React project structure.
- After the setup is complete, navigate into the project directory:
cd my-react-app
- Start the development server:
npm start
Your browser should automatically open http://localhost:3000
and display the default React welcome page.
Step 3: Setting Up the Node.js Backend
Now that we have a React frontend, let's set up a basic Node.js backend.
- In the root directory (outside the
my-react-app
folder), create a new directory for your backend:
mkdir my-node-backend
cd my-node-backend
- Initialize a new Node.js project:
npm init -y
This command creates a package.json
file, which will keep track of your project's dependencies.
- Install the necessary packages:
npm install express cors
- Express is a popular Node.js framework for building web servers.
- CORS (Cross-Origin Resource Sharing) is a middleware that allows your frontend and backend to communicate when they are on different domains or ports.
- Create a new file called
server.js
in themy-node-backend
directory and add the following code:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.get('/api/message', (req, res) => {
res.json({ message: 'Hello from the backend!' });
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This simple server listens on port 5000 and provides a single API endpoint that sends a JSON message.
- Start your Node.js server:
node server.js
Now, your backend is running on http://localhost:5000
.
Step 4: Connecting React to Node.js
To connect your React frontend with the Node.js backend, follow these steps:
- In your React project directory (
my-react-app
), opensrc/App.js
and replace its contents with the following code:
import React, { useEffect, useState } from 'react';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('http://localhost:5000/api/message')
.then(response => response.json())
.then(data => setMessage(data.message));
}, []);
return (
<div className="App">
<h1>{message}</h1>
</div>
);
}
export default App;
This code fetches the message from your Node.js server and displays it on the page.
- Save the file, and your React app should automatically reload. If everything is set up correctly, you should see the message "Hello from the backend!" on the screen.
Step 5: Running Both Servers
To keep both the React and Node.js servers running at the same time, you’ll need to open two terminal windows or tabs:
- In one terminal, navigate to
my-react-app
and runnpm start
. - In the other terminal, navigate to
my-node-backend
and runnode server.js
.
This setup allows your React app to fetch data from the Node.js backend.
Conclusion
Congratulations! You've just created a basic React application with a Node.js backend. This setup is a great starting point for building more complex web applications. From here, you can expand your app by adding more features, routes, and API endpoints. The sky’s the limit!
Happy coding!
Posted on August 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 17, 2024