React JS UI Page

What is React.js?

React.js is a JavaScript library for building user interfaces, primarily for Single Page Applications (SPA). It allows you to create reusable UI components and manage dynamic data.

React uses:

  1. Components - Reusable UI blocks.

  2. State & Props - Manage dynamic data.

  3. Virtual DOM - Efficient updates without reloading the page.

  4. React Router - Navigation without refreshing the browser.

Project Setup:

npx create-react-app react-auth
cd react-auth
npm install
npm start

Install Required Packages:

npm install react-router-dom axios
  • react-router-dom → Enables navigation between pages.

  • axios → Used for API requests.

Step 1: App.js (Main Entry Point)

src/App.js

Explanation

  1. Imports React and React Router for navigation.

  2. Defines routes (Routes & Route):

    • /register → Shows Register page.

    • /login → Shows Login page.

    • /dashboard → Shows Dashboard page.

  3. Wraps everything inside <Router> to manage navigation.

Step 2: Register Component

src/components/Register.js

Explanation

  1. useState() → Manages form data.

  2. handleChange() → Updates state when user types.

  3. handleRegister() → Sends form data to FastAPI backend.

  4. Displays success/error message.

  5. If registration is successful, shows "Go to Login" link.

Step 3: Login Component

src/components/Login.js

Explanation

  1. useState() → Stores email/password.

  2. useNavigate() → Redirects user after login.

  3. handleLogin() → Sends credentials to the backend.

  4. Redirects user to /dashboard if login is successful.

Step 4: Dashboard Component

src/components/Dashboard.js

Explanation

  1. Simple UI to show success message.

  2. Only accessible after login.

Step 5: Add CSS Styling

src/styles/auth.css

Step 1 : Setting Up the Backend (FastAPI + MongoDB)

1. Install Dependencies

First, create a virtual environment and install dependencies:

Explanation:

  • fastapi → API framework

  • uvicorn → Server to run FastAPI

  • pymongo → Connects FastAPI to MongoDB

  • passlib[bcrypt] → Hash passwords securely

  • python-dotenv → Load environment variables

  • pydantic[email] → Email validation

2. Connect FastAPI to MongoDB

Create a .env file to store MongoDB credentials:

3. Create FastAPI App

Create a file main.py:

Final Steps

  1. Start backend API:

  2. Start frontend:

Last updated