Getting Started with ReactJS: Building a Simple React App with a Node.js Backend

vkoulianos

Vassilis Koulianos

Posted on August 17, 2024

Getting Started with ReactJS: Building a Simple React App with a Node.js Backend

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:

  1. 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.
  2. 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
Enter fullscreen mode Exit fullscreen mode

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.

  1. Open your terminal and navigate to the directory where you want to create your project.
  2. Run the following command to create a new React app:
npx create-react-app my-react-app
Enter fullscreen mode Exit fullscreen mode

This command will set up a new directory called my-react-app with a basic React project structure.

  1. After the setup is complete, navigate into the project directory:
cd my-react-app
Enter fullscreen mode Exit fullscreen mode
  1. Start the development server:
npm start
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new Node.js project:
npm init -y
Enter fullscreen mode Exit fullscreen mode

This command creates a package.json file, which will keep track of your project's dependencies.

  1. Install the necessary packages:
npm install express cors
Enter fullscreen mode Exit fullscreen mode
  • 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.
  1. Create a new file called server.js in the my-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}`);
});
Enter fullscreen mode Exit fullscreen mode

This simple server listens on port 5000 and provides a single API endpoint that sends a JSON message.

  1. Start your Node.js server:
node server.js
Enter fullscreen mode Exit fullscreen mode

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:

  1. In your React project directory (my-react-app), open src/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;
Enter fullscreen mode Exit fullscreen mode

This code fetches the message from your Node.js server and displays it on the page.

  1. 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:

  1. In one terminal, navigate to my-react-app and run npm start.
  2. In the other terminal, navigate to my-node-backend and run node 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!

💖 💪 🙅 🚩
vkoulianos
Vassilis Koulianos

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