How To Create React.js Login App Using PHP API

React.js Login App Using PHP API

Building a login system is a fundamental aspect of many web applications. In this tutorial, you will learn how to create a simple login and signup system in React.js with a basic PHP login API for handling user registration and authentication.

Prerequisites to Build this React.js + PHP Login App:

Before we begin, ensure you have the following installed:

  • Node.js and npm (Node Package Manager)
  • PHP installed and running on your local server (e.g., Apache)
  • Basic understanding of ReactJS and HTTP requests

In this project we will use a basic login and registration API created in PHP. Here is the PHP login api project tutorial. First you have to build this, then you can go further.

Setting Up the React.js Project:

Run the following command to create a new React project using Vite. Enter the project name react-php-login-app, and then choose the react.

npm create vite@latest

After that go inside the project folder and run npm install:

cd react-php-login-app
npm install

In this project we will use the “react-router-dom” for routing. So install it also:

npm i react-router-dom

Here’s a basic structure for this project:

src/
├── components/
│   ├── Login.jsx
│   ├── Register.jsx
│   └── Profile.jsx
├── App.jsx
├── main.jsx
└── index.css

Creating the React.js + PHP Login & Registration App

First of all create components folder inside src folder where the three app components will be created. Register.jsx, Login.jsx, and Profile.jsx.

1. Register Component (Register.jsx):

The following Register.jsx code creates a simple registration form for the React Login application that interacts with a backend PHP API for user registration.

import { useRef, useState } from "react";
import { Link } from "react-router-dom";

const Register = () => {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const nameInputRef = useRef();
    const emailInputRef = useRef();
    const passwordInputRef = useRef();

    const handleSubmit = async (e) => {
        e.preventDefault();

        if (isSubmitting) return;
        setIsSubmitting(true);

        const name = nameInputRef.current.value.trim();
        const email = emailInputRef.current.value.trim().toLowerCase();
        const password = passwordInputRef.current.value.trim();

        if (!name || !email || !password) {
            setIsSubmitting(false);
            alert("Please fill in all required fields correctly.");
            return;
        }

        try {
            const res = await fetch("http://localhost/login-api/register.php", {
                method: "POST",
                body: JSON.stringify({
                    name,
                    email,
                    password,
                }),
            });
            const data = await res.json();

            if (data.status === 201) {
                e.target.reset();
                alert(data.message);
            } else if (typeof data.message !== "undefined") {
                alert(data.message);
            } else {
                console.log(data);
                alert("Something going wrong. See console.");
            }
        } catch (err) {
            alert(err.message);
            console.log(err);
        } finally {
            setIsSubmitting(false);
        }
    };
    return (
        <>
            <h2>Sign Up</h2>
            <form action="" method="post" onSubmit={handleSubmit}>
                <label htmlFor="username">Name:</label>
                <input
                    type="text"
                    name="username"
                    id="username"
                    placeholder="Enter your name"
                    ref={nameInputRef}
                    required
                />
                <label htmlFor="email">Email:</label>
                <input
                    type="email"
                    name="email"
                    id="email"
                    placeholder="Entery your email"
                    ref={emailInputRef}
                    required
                />
                <label htmlFor="password">Password:</label>
                <input
                    type="password"
                    name="password"
                    id="password"
                    placeholder="Enter new password"
                    ref={passwordInputRef}
                    required
                />
                <button type="submit">Sign Up</button>{" "}
                <Link to="/login">Login</Link>
            </form>
        </>
    );
};

export default Register;

2. Login Component (Login.jsx):

The Login.jsx code defines a React component for a login form that sends user credentials to a backend PHP API for authentication, manages form submission state, and navigates between login and signup routes.

import { useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";

const Login = ({ setIsLoggedIn }) => {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const navigation = useNavigate();
    const emailInputRef = useRef();
    const passwordInputRef = useRef();
    const handleSubmit = async (e) => {
        e.preventDefault();

        if (isSubmitting) return;
        setIsSubmitting(true);

        const email = emailInputRef.current.value.trim().toLowerCase();
        const password = passwordInputRef.current.value.trim();

        if (!email || !password) {
            setIsSubmitting(false);
            alert("Please fill in all required fields correctly.");
            return;
        }

        try {
            const res = await fetch("http://localhost/login-api/login.php", {
                method: "POST",
                body: JSON.stringify({
                    email,
                    password,
                }),
            });
            const data = await res.json();

            if (data.status === 200) {
                e.target.reset();
                localStorage.setItem("token", data.token);
                setIsLoggedIn(true);
                navigation("/");
            } else if (typeof data.message !== "undefined") {
                alert(data.message);
            } else {
                console.log(data);
                alert("Something going wrong. See console.");
            }
        } catch (err) {
            alert(err.message);
            console.log(err);
        } finally {
            setIsSubmitting(false);
        }
    };
    return (
        <>
            <h2>Login</h2>
            <form action="" method="post" onSubmit={handleSubmit}>
                <label htmlFor="email">Email:</label>
                <input
                    type="email"
                    name="email"
                    id="email"
                    placeholder="Entery your email"
                    ref={emailInputRef}
                    required
                />
                <label htmlFor="password">Password:</label>
                <input
                    type="password"
                    name="password"
                    id="password"
                    placeholder="Enter new password"
                    ref={passwordInputRef}
                    required
                />
                <button type="submit">Login</button>{" "}
                <Link to="/signup">Sign Up</Link>
            </form>
        </>
    );
};

export default Login;

3. Profile Component (Profile.jsx):

The Profile.jsx code defines a React component for displaying a user profile fetched from a backend PHP API using an authentication token stored in local storage, with functionality for logging out and redirecting to the login page.

import { useState } from "react";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

const Profile = ({ setIsLoggedIn }) => {
    const navigate = useNavigate();
    const [user, setUser] = useState(null);
    const [msg, setMsg] = useState("Loading...");
    useEffect(() => {
        const getToken = localStorage.getItem("token");

        (async () => {
            try {
                const res = await fetch("http://localhost/login-api/home.php", {
                    headers: {
                        Authorization: `Bearer ${getToken}`,
                    },
                });
                const data = await res.json();

                if (data.status === 200) {
                    setUser(data);
                } else if (data.status === 401) {
                    handleLogout();
                } else if (typeof data.message !== "undefined") {
                    setMsg(data.message);
                } else {
                    setMsg("Something going wrong. Check the console.");
                    console.log(data);
                }
            } catch (err) {
                setMsg(err.message);
                console.log(err);
            }
        })();
    }, []);

    const handleLogout = () => {
        setIsLoggedIn(false);
        localStorage.removeItem("token");
        navigate("/login");
    };

    return (
        <div>
            {user === null ? (
                <p>{msg}</p>
            ) : (
                <>
                    <h2>User Profile</h2>
                    <ul style={{ fontSize: "20px" }}>
                        <li>
                            <strong>Id:</strong> {user.id}
                        </li>
                        <li>
                            <strong>Name:</strong> {user.name}
                        </li>
                        <li>
                            <strong>Email:</strong> {user.email}
                        </li>
                    </ul>
                    <button onClick={handleLogout}>Logout</button>
                </>
            )}
        </div>
    );
};

export default Profile;

4. App Component (App.jsx):

This App.jsx component will be at the root of the src folder. The following App.jsx code sets up React Router for handling routes, with conditional rendering based on the user’s authentication status, displaying either a user profile, login, or registration component, and handling redirects appropriately.

import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import Register from "./components/Register";
import Login from "./components/Login";
import Profile from "./components/Profile";
import { useEffect } from "react";
import { useState } from "react";

function App() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    useEffect(() => {
        const token = localStorage.getItem("token");
        if (token) {
            setIsLoggedIn(true);
        }
    }, []);
    return (
        <BrowserRouter>
            <Routes>
                {isLoggedIn ? (
                    <Route
                        path="/"
                        element={<Profile setIsLoggedIn={setIsLoggedIn} />}
                    />
                ) : (
                    <>
                        <Route
                            path="/login"
                            element={<Login setIsLoggedIn={setIsLoggedIn} />}
                        />
                        <Route path="/signup" element={<Register />} />
                    </>
                )}
                <Route
                    path="*"
                    element={<Navigate to={isLoggedIn ? "/" : "/login"} />}
                />
            </Routes>
        </BrowserRouter>
    );
}

export default App;

5. The Main React.js file (main.jsx):

The following main.jsx code initializes a React root, rendering the App component wrapped in React.StrictMode to ensure stricter checks for potential issues during development, and applies global CSS styling.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

6. Stylesheet for this Reac.js Login & Sign-up Application

In this project we used water.css. So put the following water.css importing code in your index.css file:

@import url("https://cdn.jsdelivr.net/npm/water.css@2/out/water.css");

Run and Test the React.js + PHP Login & Signup App:

Congratulations! You’ve successfully built a simple login system using ReactJS with React Router, integrated with a basic PHP login API. Now run this app and test it:

npm run dev

This is a very simple project for giving you an Idea how to create a login and registration app in react.js using backend API. Hope you like this. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy