Table of Contents
Building a Basic Full-Stack Application with React.js and Express.js for Beginners
In this comprehensive guide, we will walk through the process of creating a basic full-stack application using React.js for the frontend and Express.js for the backend. This tutorial is designed for beginners and will cover setting up your environment, creating a simple user interface, and integrating it with a backend server.
Part 1: Setting Up the React.js Frontend
Prerequisites
Before starting, ensure you have Node.js and npm installed on your computer, as they are essential for React.js development.
Step 1: Installing Create React App
Create React App is a comfortable environment for learning React and is the best way to start building a new single-page application in React. Install it by running:
npx create-react-app my-react-app
Replace my-react-app
with your desired project name.
File Structure Overview
After creating your project, your file structure should look like this:
my-react-app/
|-- node_modules/
|-- public/
| |-- index.html
|-- src/
| |-- components/
| | |-- UserProfile.js
| |-- App.js
| |-- index.js
|-- package.json
Code language: PHP (php)
Understanding the Project Structure
Navigate to your project directory:
cd my-react-app
Key parts of the structure include:
- node_modules/: Contains all your project dependencies.
- public/: Holds static files, like your main
index.html
. - src/: Where your React.js source files reside.
- components/: For React components.
- App.js: The main React component.
- index.js: The entry point of your React app.
Step 2: Building Your First Component
Open src/App.js
. This file is the main component in your React app and is a good starting point.
App.js:
import React from 'react';
function App() {
return (
<div className="App">
<h1>Welcome to My React App</h1>
{/* Components will be added here */}
</div>
);
}
export default App;
Code language: JavaScript (javascript)
Step 3: Adding User Profile Functionality
Creating the UserProfile Component
In the src/components/
directory, create UserProfile.js
. This component will handle user data input.
UserProfile.js:
import React, { useState } from 'react';
function UserProfile() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
// Implement the logic to send data to the backend
console.log(username, password);
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input type="text" value={username} onChange={e => setUsername(e.target.value)} />
</label>
<label>
Password:
<input type="password" value={password} onChange={e => setPassword(e.target.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default UserProfile;
Code language: JavaScript (javascript)
Integrating UserProfile in App.js
In App.js
, import and use the UserProfile
component.
App.js (updated):
import React from 'react';
import UserProfile from './components/UserProfile';
function App() {
return (
<div className="App">
<h1>Welcome to My React App</h1>
<UserProfile />
</div>
);
}
export default App;
Code language: JavaScript (javascript)
Step 4: Running the Application
To start your React app, run:
npm start
This command runs the app in development mode. Open http://localhost:3000
to view it in the browser.
Check out the React.js documentation to learn more about it’s library.
Part 2: Setting Up the Express.js Backend
Step 1: Initialize a New Node.js Project
Create a new directory for your backend (outside of your React project directory). Initialize a Node.js project:
mkdir my-backend
cd my-backend
npm init -y
Step 2: Installing Express and Body-Parser
Install Express and Body-Parser, which will be used to create your server and handle incoming JSON payloads:
npm install express body-parser
Step 3: Creating the Express Server
In the my-backend
directory, create a file named server.js
. This file will contain the server code.
server.js:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
let users = []; // Mock database
app.post('/register', (req, res) => {
const { username, password } = req.body;
users.push({ username, password }); // In a real app, hash the password
res.status(200).json({ message: 'User registered successfully' });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Code language: PHP (php)
Step 4: Running the Server
Run your Express server:
node server.js
Code language: CSS (css)
Your server will listen for requests at http://localhost:3000
.
Part 3: Integrating Frontend with Backend
Step 1: Installing Axios in React Project
Install Axios in your React project to make HTTP requests:
npm install axios
Step 2: Updating UserProfile for API Interaction
Update UserProfile.js
in your React project to send user data to the Express server using Axios.
UserProfile.js (updated):
import React, { useState } from 'react';
import axios from 'axios';
function UserProfile() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post('http://localhost:3000/register', { username, password });
alert(response.data.message);
} catch (error) {
console.error('There was an error!', error);
}
};
return (
<form onSubmit={handleSubmit}>
{/* Form inputs and submit button */}
</form>
);
}
export default UserProfile;
Code language: JavaScript (javascript)
Running the Full-Stack Application
- Run the Backend: Ensure the Express server is started (
node server.js
). - Run the Frontend: Start the React app (
npm start
). - Interact with the App: Use the form in your React app to register users and observe the server’s response.
Integrating an External API
Incorporating an external API into your React application is similar to how you interacted with your Express backend. Use Axios to send requests to the API, process the responses, and update your component state accordingly.
Conclusion
You’ve now built a basic full-stack application using React.js and Express.js, a significant first step into the realm of full-stack development. As you continue to learn, focus on understanding each part of the stack more deeply, experiment with different features, and gradually take on more complex projects, soon you will be ready to start your own website click here for a comprehensive guide. Remember, every expert was once a beginner. Your journey in web development will be filled with continuous learning and exciting challenges. Happy coding!