<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: code lover</title>
    <description>The latest articles on DEV Community by code lover (@codelover405).</description>
    <link>https://dev.to/codelover405</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1054901%2Fffde9efe-0d31-4185-ac7e-39b42ab08378.png</url>
      <title>DEV Community: code lover</title>
      <link>https://dev.to/codelover405</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/codelover405"/>
    <language>en</language>
    <item>
      <title>todo</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Fri, 04 Apr 2025 04:51:21 +0000</pubDate>
      <link>https://dev.to/codelover405/todo-40li</link>
      <guid>https://dev.to/codelover405/todo-40li</guid>
      <description>&lt;h2&gt;
  
  
  Backend
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;npm i bcryptjs cors dotenv express joi jsonwebtoken mongoose nodemon&lt;/code&gt;&lt;br&gt;
folder structure&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnyzv3lnoor40ki1uvd4p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnyzv3lnoor40ki1uvd4p.png" alt="Image description" width="800" height="810"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;controllers&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;controllers/authController.js
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const User = require("../models/User");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const { registerSchema, loginSchema } = require("../utils/authValidation");

const generateToken = (userId) =&amp;gt; {
  return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: "7d" });
};

const registerUser = async (req, res) =&amp;gt; {
  const { error } = registerSchema.validate(req.body);
  if (error) return res.status(400).json({ msg: error.details[0].message });

  try {
    let user = await User.findOne({ email: req.body.email });
    if (user) return res.status(400).json({ msg: "User already exists" });

    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

    user = new User({ ...req.body, password: hashedPassword });
    await user.save();

    res.status(201).json({
      msg: "User registered successfully",
      token: generateToken(user.id),
      user: { id: user.id, name: user.name, email: user.email },
    });
  } catch (error) {
    res.status(500).json({ msg: "Server error" });
  }
};

const loginUser = async (req, res) =&amp;gt; {
  const { error } = loginSchema.validate(req.body);
  if (error) return res.status(400).json({ msg: error.details[0].message });

  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) return res.status(400).json({ msg: "Invalid credentials" });

    const isMatch = await bcrypt.compare(req.body.password, user.password);
    if (!isMatch) return res.status(400).json({ msg: "Invalid credentials" });

    res.json({
      msg: "User login successfully",
      token: generateToken(user.id),
      user: { id: user.id, name: user.name, email: user.email },
    });
  } catch (error) {
    res.status(500).json({ msg: "Server error" });
  }
};

module.exports = { registerUser, loginUser };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;controllers/todoController.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Todo = require("../models/Todo");
const { todoSchema } = require("../utils/todoValidation");

const createTodo = async (req, res) =&amp;gt; {
  const { error } = todoSchema.validate(req.body);
  if (error) return res.status(400).json({ msg: error.details[0].message });

  try {
    const todo = new Todo({ ...req.body, user: req.user });
    await todo.save();
    res.status(201).json(todo);
  } catch (error) {
    res.status(500).json({ msg: "Server error" });
  }
};

const getTodos = async (req, res) =&amp;gt; {
  try {
    const todos = await Todo.find({ user: req.user }).sort({ createdAt: -1 });
    res.json(todos);
  } catch (error) {
    res.status(500).json({ msg: "Server error" });
  }
};

const updateTodo = async (req, res) =&amp;gt; {
  const { error } = todoSchema.validate(req.body);
  if (error) return res.status(400).json({ msg: error.details[0].message });

  try {
    const todo = await Todo.findOneAndUpdate(
      { _id: req.params.id, user: req.user },
      req.body,
      { new: true }
    );
    if (!todo) return res.status(404).json({ msg: "Todo not found" });
    res.json(todo);
  } catch (error) {
    res.status(500).json({ msg: "Server error" });
  }
};

const deleteTodo = async (req, res) =&amp;gt; {
  try {
    const todo = await Todo.findOneAndDelete({
      _id: req.params.id,
      user: req.user,
    });
    if (!todo) return res.status(404).json({ msg: "Todo not found" });
    res.json({ msg: "Todo deleted successfully" });
  } catch (error) {
    res.status(500).json({ msg: "Server error" });
  }
};

module.exports = { createTodo, getTodos, updateTodo, deleteTodo };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;middleware:-&lt;/strong&gt;&lt;br&gt;
middleware/authMiddleware.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const jwt = require("jsonwebtoken");

const protect = (req, res, next) =&amp;gt; {
  const authHeader = req.header("Authorization");

  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return res.status(401).json({ msg: "No token, authorization denied" });
  }

  const token = authHeader.split(" ")[1]; // Extract token after "Bearer "

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.userId;
    next();
  } catch (error) {
    res.status(401).json({ msg: "Invalid token" });
  }
};

module.exports = protect;
**models:-**
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;models/Todo.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");

const todoSchema = new mongoose.Schema(
  {
    user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
    title: { type: String, required: true },
    description: { type: String },
    priority: {
      type: String,
      enum: ["low", "medium", "high"],
      default: "medium",
    },
    status: {
      type: String,
      enum: ["pending", "completed"],
      default: "pending",
    },
    dueDate: { type: Date, required: true },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Todo", todoSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;models/User.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");

const userSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
  },
  { timestamps: true }
);

module.exports = mongoose.model("User", userSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;routes:-&lt;/strong&gt;&lt;br&gt;
routes/authRoutes.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const { registerUser, loginUser } = require("../controllers/authController");

const router = express.Router();

router.post("/register", registerUser);

router.post("/login", loginUser);

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;routes/todoRoutes.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const {
  createTodo,
  getTodos,
  updateTodo,
  deleteTodo,
} = require("../controllers/todoController");
const protect = require("../middleware/authMiddleware");

const router = express.Router();

router.post("/", protect, createTodo);
router.get("/", protect, getTodos);
router.put("/:id", protect, updateTodo);
router.delete("/:id", protect, deleteTodo);

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;utils:-&lt;/strong&gt;&lt;br&gt;
utils/authValidation.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Joi = require("joi");

const registerSchema = Joi.object({
  name: Joi.string().min(3).max(30).required(),
  email: Joi.string().email().required(),
  password: Joi.string().min(6).required(),
});

const loginSchema = Joi.object({
  email: Joi.string().email().required(),
  password: Joi.string().min(6).required(),
});

module.exports = { registerSchema, loginSchema };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;utils/jwt.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const generateToken = (userId) =&amp;gt; {
  return jwt.sign({ id: userId }, process.env.JWT_SECRET, {
    expiresIn: "1d",
  });
};

const verifyToken = (token) =&amp;gt; {
  return jwt.verify(token, process.env.JWT_SECRET);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;utils/todoValidation.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Joi = require("joi");

const todoSchema = Joi.object({
  title: Joi.string().min(3).max(100).required(),
  description: Joi.string().max(500).allow(""),
  priority: Joi.string().valid("low", "medium", "high").default("medium"),
  status: Joi.string().valid("pending", "completed").default("pending"),
  dueDate: Joi.date().greater("now").required(),
});

module.exports = { todoSchema };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;.env&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PORT=5000
MONGO_URI=
JWT_SECRET=i-am-utsav-ioopen-source
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;config.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");
require("dotenv").config();

const connectDB = async () =&amp;gt; {
  try {
    await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log("MongoDB Connected...");
  } catch (error) {
    console.error("MongoDB Connection Failed:", error);
    process.exit(1);
  }
};

module.exports = connectDB;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;server.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const dotenv = require("dotenv");
const cors = require("cors");
const connectDB = require("./config");

const authRoutes = require("./routes/authRoutes");
const todoRoutes = require("./routes/todoRoutes");

dotenv.config();
connectDB();

const app = express();

app.use(express.json());
app.use(cors());

app.use("/api/auth", authRoutes);
app.use("/api/todos", todoRoutes);

app.get("/", (req, res) =&amp;gt; {
  res.send("API is running...");
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () =&amp;gt; console.log(`Server running on port ${PORT}`));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;package.json&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "backend",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1",
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "bcryptjs": "^3.0.2",
    "cors": "^2.8.5",
    "dotenv": "^16.4.7",
    "express": "^4.21.2",
    "express-validator": "^7.2.1",
    "joi": "^17.13.3",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.10.1"
  },
  "devDependencies": {
    "nodemon": "^3.1.9"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Frontend
&lt;/h2&gt;

&lt;p&gt;main.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.jsx";
// import AppRouter from "./AppRouter.jsx";
import { Toaster } from "react-hot-toast";

createRoot(document.getElementById("root")).render(
  &amp;lt;StrictMode&amp;gt;
    &amp;lt;App /&amp;gt;
    {/* &amp;lt;AppRouter /&amp;gt; */}
    &amp;lt;Toaster position="top-right" /&amp;gt;
  &amp;lt;/StrictMode&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;app.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
// import Login from "./pages/Login";
// import Register from "./pages/Register";
// import Dashboard from "./pages/Dashboard";
// import { ProtectedRoute } from "./authMiddleware";

import AuthProvider from "./provider/authProvider";
import Routes from "./routes";

function App() {
  return (
    // &amp;lt;Router&amp;gt;
    //   &amp;lt;Routes&amp;gt;
    //     &amp;lt;Route path="/" element={&amp;lt;Login /&amp;gt;} /&amp;gt;
    //     &amp;lt;Route path="/register" element={&amp;lt;Register /&amp;gt;} /&amp;gt;
    //     {/* &amp;lt;Route path="/dashboard" element={&amp;lt;Dashboard /&amp;gt;} /&amp;gt; */}

    //     &amp;lt;Route
    //       path="/dashboard"
    //       element={
    //         &amp;lt;ProtectedRoute&amp;gt;
    //           &amp;lt;Dashboard /&amp;gt;
    //         &amp;lt;/ProtectedRoute&amp;gt;
    //       }
    //     /&amp;gt;
    //   &amp;lt;/Routes&amp;gt;
    // &amp;lt;/Router&amp;gt;
    &amp;lt;AuthProvider&amp;gt;
      &amp;lt;Routes /&amp;gt;
    &amp;lt;/AuthProvider&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;AppRouter.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from "react-router-dom";
import { useState, useEffect } from "react";
import Login from "./pages/Login";
import Register from "./pages/Register";
import Dashboard from "./pages/Dashboard";
// import NotFound from "./pages/NotFound";

const AppRouter = () =&amp;gt; {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() =&amp;gt; {
    const token = localStorage.getItem("token");
    setIsAuthenticated(!!token);
  }, []);

  return (
    &amp;lt;Router&amp;gt;
      &amp;lt;Routes&amp;gt;
        &amp;lt;Route
          path="/"
          element={isAuthenticated ? &amp;lt;Dashboard /&amp;gt; : &amp;lt;Navigate to="/login" /&amp;gt;}
        /&amp;gt;
        &amp;lt;Route path="/login" element={&amp;lt;Login /&amp;gt;} /&amp;gt;
        &amp;lt;Route path="/register" element={&amp;lt;Register /&amp;gt;} /&amp;gt;
        {/* &amp;lt;Route path="*" element={&amp;lt;NotFound /&amp;gt;} /&amp;gt; */}
      &amp;lt;/Routes&amp;gt;
    &amp;lt;/Router&amp;gt;
  );
};

export default AppRouter;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;authMiddleware.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useNavigate } from "react-router-dom";

export const ProtectedRoute = ({ children }) =&amp;gt; {
  const navigate = useNavigate();
  const token = localStorage.getItem("token");
  return token ? children : navigate("/");
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;index.css&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
@tailwind utilities;

html.dark {
  background-color: #121212;
  color: white;
}

.dark .bg-white {
  background-color: #1e1e1e;
}

.dark .border {
  border-color: #333;
}

.dark .shadow {
  box-shadow: 0px 4px 6px rgba(255, 255, 255, 0.1);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;App.css&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@import "tailwindcss";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;utils/axios.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from "axios";

const API = axios.create({
  baseURL: "http://localhost:5000/api",
});

API.interceptors.request.use(
  (config) =&amp;gt; {
    const token = localStorage.getItem("token");
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  (error) =&amp;gt; Promise.reject(error)
);

export default API;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;routes&lt;/strong&gt;&lt;br&gt;
routes/ProtectedRoute.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "../provider/authProvider";

export const ProtectedRoute = () =&amp;gt; {
  const { token } = useAuth();

  // Check if the user is authenticated
  if (!token) {
    // If not authenticated, redirect to the login page
    return &amp;lt;Navigate to="/login" /&amp;gt;;
  }

  // If authenticated, render the child routes
  return &amp;lt;Outlet /&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;routes/index.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { useAuth } from "../provider/authProvider";
import { ProtectedRoute } from "./ProtectedRoute";
import Login from "../pages/Login";
// import Logout from "../pages/Logout";
import Dashboard from "../pages/Dashboard";
import TodoList from "../components/second/TodoList";

const Routes = () =&amp;gt; {
  const { token } = useAuth();

  // Define public routes accessible to all users
  const routesForPublic = [
    {
      path: "/service",
      element: &amp;lt;div&amp;gt;Service Page&amp;lt;/div&amp;gt;,
    },
    {
      path: "/about-us",
      element: &amp;lt;div&amp;gt;About Us&amp;lt;/div&amp;gt;,
    },
  ];

  // Define routes accessible only to authenticated users
  const routesForAuthenticatedOnly = [
    {
      path: "/",
      element: &amp;lt;ProtectedRoute /&amp;gt;, // Wrap the component in ProtectedRoute
      children: [
        {
          path: "",
          element: &amp;lt;Dashboard /&amp;gt;,
          // element: &amp;lt;TodoList /&amp;gt;,
        },
        {
          path: "/profile",
          element: &amp;lt;div&amp;gt;User Profile&amp;lt;/div&amp;gt;,
        },
        // {
        //   path: "/logout",
        //   element: &amp;lt;Logout /&amp;gt;,
        // },
      ],
    },
  ];

  // Define routes accessible only to non-authenticated users
  const routesForNotAuthenticatedOnly = [
    // {
    //   path: "/",
    //   element: &amp;lt;div&amp;gt;Home Page&amp;lt;/div&amp;gt;,
    // },
    {
      path: "/login",
      element: &amp;lt;Login /&amp;gt;,
    },
  ];

  // Combine and conditionally include routes based on authentication status
  const router = createBrowserRouter([
    ...routesForPublic,
    ...(!token ? routesForNotAuthenticatedOnly : []),
    ...routesForAuthenticatedOnly,
  ]);

  // Provide the router configuration using RouterProvider
  return &amp;lt;RouterProvider router={router} /&amp;gt;;
};

export default Routes;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;provider&lt;/strong&gt;&lt;br&gt;
provider/authProvider.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from "axios";
import { createContext, useContext, useEffect, useMemo, useState } from "react";

const AuthContext = createContext();

const AuthProvider = ({ children }) =&amp;gt; {
  // State to hold the authentication token
  const [token, setToken_] = useState(localStorage.getItem("token"));

  // Function to set the authentication token
  const setToken = (newToken) =&amp;gt; {
    setToken_(newToken);
  };

  useEffect(() =&amp;gt; {
    if (token) {
      axios.defaults.headers.common["Authorization"] = "Bearer " + token;
      localStorage.setItem("token", token);
    } else {
      delete axios.defaults.headers.common["Authorization"];
      localStorage.removeItem("token");
    }
  }, [token]);

  // Memoized value of the authentication context
  const contextValue = useMemo(
    () =&amp;gt; ({
      token,
      setToken,
    }),
    [token]
  );

  // Provide the authentication context to the children components
  return (
    &amp;lt;AuthContext.Provider value={contextValue}&amp;gt;{children}&amp;lt;/AuthContext.Provider&amp;gt;
  );
};

export const useAuth = () =&amp;gt; {
  return useContext(AuthContext);
};

export default AuthProvider;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;pages&lt;/strong&gt;&lt;br&gt;
pages/Dashboard.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from "react";
import API from "../utils/axios";
import TodoModal from "../components/TodoModal";
import toast from "react-hot-toast";
import DarkModeToggle from "../components/DarkModeToggle";
import { useAuth } from "../provider/authProvider";
import { useNavigate } from "react-router-dom";

const Dashboard = () =&amp;gt; {
  const { setToken } = useAuth();
  const navigate = useNavigate();

  const [todos, setTodos] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [editTodo, setEditTodo] = useState(null);
  const [statusFilter, setStatusFilter] = useState("all");
  const [sortOrder, setSortOrder] = useState("newest");
  const [filteredTodos, setFilteredTodos] = useState([]);
  const [loading, setLoading] = useState(false); // Add loading state

  const fetchTodos = async () =&amp;gt; {
    setLoading(true); // Start loading
    try {
      const res = await API.get("/todos");
      setTodos(res.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false); // End loading
    }
  };

  useEffect(() =&amp;gt; {
    fetchTodos();
  }, []);

  useEffect(() =&amp;gt; {
    let updatedTodos = [...todos];

    if (statusFilter !== "all") {
      updatedTodos = updatedTodos.filter((todo) =&amp;gt;
        statusFilter === "completed"
          ? todo.status === "completed"
          : todo.status === "pending"
      );
    }

    if (sortOrder === "newest") {
      updatedTodos.sort((a, b) =&amp;gt; new Date(b.dueDate) - new Date(a.dueDate));
    } else {
      updatedTodos.sort((a, b) =&amp;gt; new Date(a.dueDate) - new Date(b.dueDate));
    }

    setFilteredTodos(updatedTodos);
  }, [statusFilter, sortOrder, todos]);

  const deleteTodo = async (id) =&amp;gt; {
    try {
      await API.delete(`/todos/${id}`);
      setTodos((prev) =&amp;gt; prev.filter((todo) =&amp;gt; todo._id !== id));
      toast.success("To-Do deleted successfully!");
    } catch (err) {
      console.log(err);
      toast.error("Failed to delete To-Do!");
    }
  };

  // const logOut = () =&amp;gt; {
  //   localStorage.removeItem("token");
  //   window.location.href = "/";
  // };



  const handleLogout = () =&amp;gt; {
    setToken();
    navigate("/", { replace: true });
  };

  return (
    &amp;lt;div className="p-6"&amp;gt;
      &amp;lt;DarkModeToggle /&amp;gt;
      &amp;lt;button className="p-3 bg-gray-500 cursor-pointer" onClick={handleLogout}&amp;gt;
        Logout
      &amp;lt;/button&amp;gt;{" "}
      &amp;lt;h2 className="text-xl font-bold mb-4"&amp;gt;To-Do List&amp;lt;/h2&amp;gt;
      &amp;lt;button
        className="p-2 bg-green-500 text-white rounded mb-4"
        onClick={() =&amp;gt; setModalOpen(true)}
        aria-label="Add a new to-do"
      &amp;gt;
        Add To-Do
      &amp;lt;/button&amp;gt;
      &amp;lt;div className="flex gap-4 mb-4"&amp;gt;
        &amp;lt;select
          className="p-2 border rounded"
          onChange={(e) =&amp;gt; setStatusFilter(e.target.value)}
          value={statusFilter}
        &amp;gt;
          &amp;lt;option value="all"&amp;gt;All&amp;lt;/option&amp;gt;
          &amp;lt;option value="completed"&amp;gt;Completed&amp;lt;/option&amp;gt;
          &amp;lt;option value="pending"&amp;gt;Pending&amp;lt;/option&amp;gt;
        &amp;lt;/select&amp;gt;

        &amp;lt;select
          className="p-2 border rounded"
          onChange={(e) =&amp;gt; setSortOrder(e.target.value)}
          value={sortOrder}
        &amp;gt;
          &amp;lt;option value="newest"&amp;gt;Newest First&amp;lt;/option&amp;gt;
          &amp;lt;option value="oldest"&amp;gt;Oldest First&amp;lt;/option&amp;gt;
        &amp;lt;/select&amp;gt;

        &amp;lt;button
          className="p-2 bg-green-500 text-white rounded"
          onClick={() =&amp;gt; setModalOpen(true)}
        &amp;gt;
          Add To-Do
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      {
        loading ? (
          &amp;lt;p className="text-center"&amp;gt;Loading todos...&amp;lt;/p&amp;gt;
        ) : (
          &amp;lt;table className="w-full mt-4 border-collapse border border-gray-300"&amp;gt;
            &amp;lt;thead&amp;gt;
              &amp;lt;tr className="bg-gray-200"&amp;gt;
                &amp;lt;th scope="col" className="border p-2"&amp;gt;Title&amp;lt;/th&amp;gt;
                &amp;lt;th className="border p-2"&amp;gt;Description&amp;lt;/th&amp;gt;
                &amp;lt;th className="border p-2"&amp;gt;Priority&amp;lt;/th&amp;gt;
                &amp;lt;th className="border p-2"&amp;gt;Due Date&amp;lt;/th&amp;gt;
                &amp;lt;th className="border p-2"&amp;gt;Status&amp;lt;/th&amp;gt;
                &amp;lt;th className="border p-2"&amp;gt;Actions&amp;lt;/th&amp;gt;
              &amp;lt;/tr&amp;gt;
            &amp;lt;/thead&amp;gt;
            &amp;lt;tbody&amp;gt;
              {/* {todos.map((todo) =&amp;gt; (
            &amp;lt;tr key={todo._id} className="border"&amp;gt;
              &amp;lt;td className="border p-2"&amp;gt;{todo.title}&amp;lt;/td&amp;gt;
              &amp;lt;td className="border p-2"&amp;gt;{todo.description}&amp;lt;/td&amp;gt;
              &amp;lt;td className="border p-2"&amp;gt;{todo.priority}&amp;lt;/td&amp;gt;
              &amp;lt;td className="border p-2"&amp;gt;
                {new Date(todo.dueDate).toLocaleDateString()}
              &amp;lt;/td&amp;gt;
              &amp;lt;td className="border p-2"&amp;gt;
                {todo.status === "completed" ? (
                  &amp;lt;span className="text-green-500"&amp;gt;Completed&amp;lt;/span&amp;gt;
                ) : (
                  &amp;lt;span className="text-red-500"&amp;gt;Pending&amp;lt;/span&amp;gt;
                )}
              &amp;lt;/td&amp;gt;

              &amp;lt;td className="border p-2 flex gap-2"&amp;gt;
                &amp;lt;button
                  className="p-1 bg-yellow-500 text-white rounded"
                  onClick={() =&amp;gt; {
                    setEditTodo(todo);
                    setModalOpen(true);
                  }}
                &amp;gt;
                  Edit
                &amp;lt;/button&amp;gt;
                &amp;lt;button
                  className="p-1 bg-red-500 text-white rounded"
                  onClick={() =&amp;gt; deleteTodo(todo._id)}
                &amp;gt;
                  Delete
                &amp;lt;/button&amp;gt;
              &amp;lt;/td&amp;gt;
            &amp;lt;/tr&amp;gt;
          ))} */}

              {filteredTodos.map((todo) =&amp;gt; (
                &amp;lt;tr key={todo._id} className="border"&amp;gt;
                  &amp;lt;td className="border p-2"&amp;gt;{todo.title}&amp;lt;/td&amp;gt;
                  &amp;lt;td className="border p-2"&amp;gt;{todo.description}&amp;lt;/td&amp;gt;
                  &amp;lt;td className="border p-2"&amp;gt;{todo.priority}&amp;lt;/td&amp;gt;
                  &amp;lt;td className="border p-2"&amp;gt;
                    {new Date(todo.dueDate).toLocaleDateString()}
                  &amp;lt;/td&amp;gt;
                  &amp;lt;td className="border p-2"&amp;gt;
                    {todo.status === "completed" ? (
                      &amp;lt;span className="text-green-500"&amp;gt;Completed&amp;lt;/span&amp;gt;
                    ) : (
                      &amp;lt;span className="text-red-500"&amp;gt;Pending&amp;lt;/span&amp;gt;
                    )}
                  &amp;lt;/td&amp;gt;
                  &amp;lt;td className="border p-2 flex gap-2"&amp;gt;
                    &amp;lt;button
                      className="p-1 bg-yellow-500 text-white rounded"
                      onClick={() =&amp;gt; {
                        setEditTodo(todo);
                        setModalOpen(true);
                      }}
                    &amp;gt;
                      Edit
                    &amp;lt;/button&amp;gt;
                    &amp;lt;button
                      className="p-1 bg-red-500 text-white rounded"
                      onClick={() =&amp;gt; deleteTodo(todo._id)}
                    &amp;gt;
                      Delete
                    &amp;lt;/button&amp;gt;
                  &amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
              ))}
            &amp;lt;/tbody&amp;gt;
          &amp;lt;/table&amp;gt;
        )}
      &amp;lt;TodoModal
        isOpen={modalOpen}
        onClose={() =&amp;gt; {
          setModalOpen(false);
          setEditTodo(null);
        }}
        refreshTodos={fetchTodos}
        editTodo={editTodo}
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Dashboard;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;pages/Login.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useNavigate } from "react-router-dom";
import toast from "react-hot-toast";
import { Formik } from "formik";
import * as Yup from "yup";
import API from "../utils/axios";
import { useAuth } from "../provider/authProvider";

const LoginInitialValues = {
  email: "",
  password: "",
};

const LogInSchema = Yup.object().shape({
  email: Yup.string()
    .email("Invalid email address")
    .required("Email is required"),
  password: Yup.string()
    .required("Password is required")
    .matches(
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&amp;amp;\*])(?=.{8,})/,
      "Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character"
    ),
});

const Login = () =&amp;gt; {
  const navigate = useNavigate();
  const { setToken } = useAuth();

  // const handleLogin = async (e) =&amp;gt; {
  //   e.preventDefault();
  //   try {
  //     const { data } = await axios.post(
  //       "http://localhost:5000/api/auth/login",
  //       { email, password }
  //     );
  //     localStorage.setItem("token", data.token);
  //     toast.success("Login successful!");
  //     navigate("/dashboard");
  //   } catch (error) {
  //     toast.error(error.response?.data?.msg || "Login failed");
  //   }
  // };

  const handleSubmit = async (values, { setSubmitting }) =&amp;gt; {
    try {
      const response = await API.post("/auth/login", {
        email: values.email,
        password: values.password,
      });
      console.log("LLLL", response);

      // localStorage.setItem("token", response.data.token);
      toast.success(response?.data?.data?.msg || "Login successfully");
      // navigate("/dashboard");
      setToken(response?.data?.token);
      navigate("/", { replace: true });
    } catch (error) {
      // console.log("error.....", error);
      toast.error(error?.response?.data?.msg || "Login failed");
    }
    setSubmitting(false);
  };

  return (
    &amp;lt;div className="flex justify-center items-center h-screen"&amp;gt;
      {/* &amp;lt;form
        onSubmit={handleLogin}
        className="bg-white p-6 rounded-lg shadow-lg"
      &amp;gt; */}
      &amp;lt;Formik
        initialValues={LoginInitialValues}
        validationSchema={LogInSchema}
        onSubmit={(values, { setSubmitting }) =&amp;gt;
          handleSubmit(values, setSubmitting)
        }
      &amp;gt;
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting,
          isValid,
        }) =&amp;gt; (
          &amp;lt;form className="space-y-2 max-w-2xl w-full" onSubmit={handleSubmit}&amp;gt;
            &amp;lt;h2 className="text-2xl font-bold mb-4"&amp;gt;Login&amp;lt;/h2&amp;gt;
            &amp;lt;input
              type="text"
              placeholder="Email Address"
              className={`border p-2 w-full ${errors.email &amp;amp;&amp;amp; touched.email ? "border-red-600" : ""
                }`}
              name="email"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            /&amp;gt;
            &amp;lt;div className="text-red-500 text-sm"&amp;gt;
              {errors.email &amp;amp;&amp;amp; touched.email &amp;amp;&amp;amp; errors.email}
            &amp;lt;/div&amp;gt;
            &amp;lt;input
              type="password"
              placeholder="Password"
              className={`border p-2 w-full ${errors.password &amp;amp;&amp;amp; touched.password ? "border-red-600" : ""
                }`}
              name="password"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.password}
            /&amp;gt;
            &amp;lt;div className="text-red-500 text-sm"&amp;gt;
              {errors.password &amp;amp;&amp;amp; touched.password &amp;amp;&amp;amp; errors.password}
            &amp;lt;/div&amp;gt;
            &amp;lt;button
              type="submit"
              className="bg-blue-500 text-white p-2 rounded w-full"
            &amp;gt;
              Login
            &amp;lt;/button&amp;gt;
            &amp;lt;div
              className="mx-auto text-center mt-2 cursor-pointer"
              onClick={() =&amp;gt; navigate("/register")}
            &amp;gt;
              Register
            &amp;lt;/div&amp;gt;
            {/* &amp;lt;/form&amp;gt; */}
          &amp;lt;/form&amp;gt;
        )}
      &amp;lt;/Formik&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Login;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;pages/Register.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useNavigate } from "react-router-dom";
import toast from "react-hot-toast";
import { Formik } from "formik";
import * as Yup from "yup";
import API from "../utils/axios";

const LoginInitialValues = {
  name: "",
  email: "",
  password: "",
  confirmPassword: "",
};

const LogInSchema = Yup.object().shape({
  name: Yup.string().required("Username is required"),
  email: Yup.string()
    .email("Invalid email address")
    .required("Email is required"),
  password: Yup.string()
    .required("Password is required")
    .matches(
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&amp;amp;\*])(?=.{8,})/,
      "Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character"
    ),
  confirmPassword: Yup.string()
    .oneOf([Yup.ref("password")], "Passwords must match")
    .min(8, "Confirm password must be at least 8 characters")
    .required("Confirm password is required"),
});

const Register = () =&amp;gt; {
  const navigator = useNavigate();
  const handleSubmit = async (values, { setSubmitting }) =&amp;gt; {
    try {
      const response = await API.post("/auth/register", {
        name: values.name,
        email: values.email,
        password: values.password,
      });
      toast.success(response?.data?.data?.msg || "Registration successfully");
      navigator("/");
    } catch (error) {
      console.log("error.....", error);
      toast.error(error?.response?.data?.msg || "Registration failed");
    }
    setSubmitting(false);
  };
  return (
    &amp;lt;div className="flex justify-center items-center h-screen"&amp;gt;
      {/* &amp;lt;form
        onSubmit={handleRegister}
        className="bg-white p-6 rounded-lg shadow-lg"
      &amp;gt; */}
      &amp;lt;Formik
        initialValues={LoginInitialValues}
        validationSchema={LogInSchema}
        onSubmit={(values, { setSubmitting }) =&amp;gt;
          handleSubmit(values, setSubmitting)
        }
      &amp;gt;
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting,
          isValid,
        }) =&amp;gt; (
          &amp;lt;form className="space-y-2 max-w-2xl w-full" onSubmit={handleSubmit}&amp;gt;
            &amp;lt;h2 className="text-2xl font-bold"&amp;gt;Register&amp;lt;/h2&amp;gt;
            &amp;lt;input
              type="text"
              placeholder="Name"
              className={`border p-2 w-full ${
                errors.name &amp;amp;&amp;amp; touched.name ? "border-red-600" : ""
              }`}
              name="name"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.name}
            /&amp;gt;
            &amp;lt;div className="text-red-500 text-sm"&amp;gt;
              {errors.name &amp;amp;&amp;amp; touched.name &amp;amp;&amp;amp; errors.name}
            &amp;lt;/div&amp;gt;
            &amp;lt;input
              type="text"
              placeholder="Email Address"
              className={`border p-2 w-full ${
                errors.email &amp;amp;&amp;amp; touched.email ? "border-red-600" : ""
              }`}
              name="email"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            /&amp;gt;
            &amp;lt;div className="text-red-500 text-sm"&amp;gt;
              {errors.email &amp;amp;&amp;amp; touched.email &amp;amp;&amp;amp; errors.email}
            &amp;lt;/div&amp;gt;
            &amp;lt;input
              type="text"
              placeholder="Password"
              className={`border p-2 w-full ${
                errors.password &amp;amp;&amp;amp; touched.password ? "border-red-600" : ""
              }`}
              name="password"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.password}
            /&amp;gt;
            &amp;lt;div className="text-red-500 text-sm"&amp;gt;
              {errors.password &amp;amp;&amp;amp; touched.password &amp;amp;&amp;amp; errors.password}
            &amp;lt;/div&amp;gt;
            &amp;lt;input
              type="password"
              placeholder="confirmPassword"
              className={`border p-2 w-full ${
                errors.confirmPassword &amp;amp;&amp;amp; touched.confirmPassword
                  ? "border-red-600"
                  : ""
              }`}
              name="confirmPassword"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.confirmPassword}
            /&amp;gt;
            &amp;lt;div className="text-red-500 text-sm"&amp;gt;
              {errors.confirmPassword &amp;amp;&amp;amp;
                touched.confirmPassword &amp;amp;&amp;amp;
                errors.confirmPassword}
            &amp;lt;/div&amp;gt;
            &amp;lt;button
              type="submit"
              className="bg-green-500 text-white p-2 rounded w-full"
            &amp;gt;
              Register
            &amp;lt;/button&amp;gt;
            &amp;lt;div
              className="mx-auto text-center mt-2 cursor-pointer"
              onClick={() =&amp;gt; navigator("/")}
            &amp;gt;
              Login
            &amp;lt;/div&amp;gt;
          &amp;lt;/form&amp;gt;
        )}
      &amp;lt;/Formik&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Register;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;components&lt;/strong&gt;&lt;br&gt;
components/DarkModeToggle.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from "react";

const DarkModeToggle = () =&amp;gt; {
  const [darkMode, setDarkMode] = useState(
    localStorage.getItem("theme") === "dark"
  );

  useEffect(() =&amp;gt; {
    if (darkMode) {
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");
    } else {
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");
    }
  }, [darkMode]);

  return (
    &amp;lt;button
      onClick={() =&amp;gt; setDarkMode(!darkMode)}
      className="p-2 bg-gray-500 text-white rounded"
    &amp;gt;
      {darkMode ? "Light Mode" : "Dark Mode"}
    &amp;lt;/button&amp;gt;
  );
};

export default DarkModeToggle;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;components/TodoModal.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import API from "../utils/axios";
import toast from "react-hot-toast";

const TodoModal = ({ isOpen, onClose, refreshTodos, editTodo }) =&amp;gt; {
  const formik = useFormik({
    initialValues: {
      title: editTodo ? editTodo.title : "",
      description: editTodo ? editTodo.description : "",
      priority: editTodo ? editTodo.priority : "low",
      dueDate: editTodo ? editTodo.dueDate.split("T")[0] : "",
      status: editTodo ? editTodo.status : "pending",
    },
    validationSchema: Yup.object({
      title: Yup.string().required("Title is required"),
      priority: Yup.string().oneOf(["low", "medium", "high"]).required(),
      dueDate: Yup.date().required("Due date is required"),
      status: Yup.string().oneOf(["pending", "completed"]).required(),
    }),
    onSubmit: async (values) =&amp;gt; {
      try {
        if (editTodo) {
          await API.put(`/todos/${editTodo._id}`, values);
          toast.success("To-Do updated successfully!");
        } else {
          await API.post("/todos", values);
          toast.success("To-Do added successfully!");
        }
        refreshTodos();
        onClose();
      } catch (err) {
        toast.error("Something went wrong!");
      }
    },
  });

  useEffect(() =&amp;gt; {
    if (editTodo) {
      formik.setValues({
        title: editTodo.title,
        priority: editTodo.priority,
        dueDate: editTodo.dueDate.split("T")[0],
        status: editTodo.status,
        description: editTodo.description,
      });
    }
  }, [editTodo]);

  return (
    isOpen &amp;amp;&amp;amp; (
      &amp;lt;div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50"&amp;gt;
        &amp;lt;div className="bg-white p-6 rounded-lg w-96"&amp;gt;
          &amp;lt;h2 className="text-xl font-bold mb-4"&amp;gt;
            {editTodo ? "Edit" : "Add"} To-Do
          &amp;lt;/h2&amp;gt;
          &amp;lt;form onSubmit={formik.handleSubmit}&amp;gt;
            &amp;lt;input
              type="text"
              name="title"
              placeholder="Title"
              className="w-full p-2 border rounded mb-2"
              {...formik.getFieldProps("title")}
            /&amp;gt;
            {formik.touched.title &amp;amp;&amp;amp; formik.errors.title &amp;amp;&amp;amp; (
              &amp;lt;p className="text-red-500"&amp;gt;{formik.errors.title}&amp;lt;/p&amp;gt;
            )}
            &amp;lt;input
              type="text"
              name="description"
              placeholder="description"
              className="w-full p-2 border rounded mb-2"
              {...formik.getFieldProps("description")}
            /&amp;gt;
            {formik.touched.description &amp;amp;&amp;amp; formik.errors.description &amp;amp;&amp;amp; (
              &amp;lt;p className="text-red-500"&amp;gt;{formik.errors.description}&amp;lt;/p&amp;gt;
            )}

            &amp;lt;select
              name="priority"
              className="w-full p-2 border rounded mb-2"
              {...formik.getFieldProps("priority")}
            &amp;gt;
              &amp;lt;option value="low"&amp;gt;Low&amp;lt;/option&amp;gt;
              &amp;lt;option value="medium"&amp;gt;Medium&amp;lt;/option&amp;gt;
              &amp;lt;option value="high"&amp;gt;High&amp;lt;/option&amp;gt;
            &amp;lt;/select&amp;gt;

            &amp;lt;select
              name="status"
              className="w-full p-2 border rounded mb-2"
              {...formik.getFieldProps("status")}
            &amp;gt;
              &amp;lt;option value="pending"&amp;gt;Pending&amp;lt;/option&amp;gt;
              &amp;lt;option value="completed"&amp;gt;Completed&amp;lt;/option&amp;gt;
            &amp;lt;/select&amp;gt;

            &amp;lt;input
              type="date"
              name="dueDate"
              className="w-full p-2 border rounded mb-2"
              {...formik.getFieldProps("dueDate")}
            /&amp;gt;
            {formik.touched.dueDate &amp;amp;&amp;amp; formik.errors.dueDate &amp;amp;&amp;amp; (
              &amp;lt;p className="text-red-500"&amp;gt;{formik.errors.dueDate}&amp;lt;/p&amp;gt;
            )}

            &amp;lt;button
              type="submit"
              className="w-full p-2 bg-blue-500 text-white rounded"
            &amp;gt;
              {editTodo ? "Update" : "Add"} To-Do
            &amp;lt;/button&amp;gt;
          &amp;lt;/form&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    )
  );
};

export default TodoModal;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;components/second/TodoForm.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// TodoForm.jsx
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import API from '../../utils/axios';

const TodoForm = ({ fetchTodos, todo = {}, isUpdate = false, closeModal }) =&amp;gt; {
    const validationSchema = Yup.object({
        title: Yup.string()
            .min(2, 'Title must be at least 2 characters')
            .max(50, 'Title must be less than 50 characters')
            .required('Title is required'),
        description: Yup.string()
            .max(200, 'Description must be less than 200 characters')
            .required('Description is required'),
        dueDate: Yup.date()
            .required('Due date is required')
            .min(new Date(), 'Due date cannot be in the past'),
        priority: Yup.string()
            .oneOf(['low', 'medium', 'high'], 'Invalid priority')
            .required('Priority is required'),
        status: Yup.string().oneOf(["pending", "completed"])
            .required('Status is required'),
    });

    const initialValues = {
        title: todo.title || '',
        description: todo.description || '',
        dueDate: todo.dueDate ? new Date(todo.dueDate).toISOString().split('T')[0] : '',
        priority: todo.priority || 'low',
        status: todo.status || 'pending',
    };

    const handleSubmit = async (values, { resetForm }) =&amp;gt; {
        try {
            if (isUpdate) {
                await API.put(`/todos/${todo._id}`, values);
                closeModal();
            } else {
                await API.post('/todos', values);
                resetForm();
            }
            fetchTodos();
        } catch (error) {
            console.error('Error submitting todo:', error);
        }
    };

    return (
        &amp;lt;Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
            enableReinitialize
        &amp;gt;
            {({ isSubmitting }) =&amp;gt; (
                &amp;lt;Form className="space-y-4"&amp;gt;
                    &amp;lt;div&amp;gt;
                        &amp;lt;label htmlFor="title" className="block text-sm font-medium text-gray-700"&amp;gt;Title&amp;lt;/label&amp;gt;
                        &amp;lt;Field
                            name="title"
                            type="text"
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                        /&amp;gt;
                        &amp;lt;ErrorMessage name="title" component="div" className="text-red-500 text-sm mt-1" /&amp;gt;
                    &amp;lt;/div&amp;gt;

                    &amp;lt;div&amp;gt;
                        &amp;lt;label htmlFor="description" className="block text-sm font-medium text-gray-700"&amp;gt;Description&amp;lt;/label&amp;gt;
                        &amp;lt;Field
                            name="description"
                            as="textarea"
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                            rows="3"
                        /&amp;gt;
                        &amp;lt;ErrorMessage name="description" component="div" className="text-red-500 text-sm mt-1" /&amp;gt;
                    &amp;lt;/div&amp;gt;

                    &amp;lt;div&amp;gt;
                        &amp;lt;label htmlFor="dueDate" className="block text-sm font-medium text-gray-700"&amp;gt;Due Date&amp;lt;/label&amp;gt;
                        &amp;lt;Field
                            name="dueDate"
                            type="date"
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                        /&amp;gt;
                        &amp;lt;ErrorMessage name="dueDate" component="div" className="text-red-500 text-sm mt-1" /&amp;gt;
                    &amp;lt;/div&amp;gt;

                    &amp;lt;div&amp;gt;
                        &amp;lt;label htmlFor="priority" className="block text-sm font-medium text-gray-700"&amp;gt;Priority&amp;lt;/label&amp;gt;
                        &amp;lt;Field
                            as="select"
                            name="priority"
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                        &amp;gt;
                            &amp;lt;option value="low"&amp;gt;Low&amp;lt;/option&amp;gt;
                            &amp;lt;option value="medium"&amp;gt;Medium&amp;lt;/option&amp;gt;
                            &amp;lt;option value="high"&amp;gt;High&amp;lt;/option&amp;gt;
                        &amp;lt;/Field&amp;gt;
                        &amp;lt;ErrorMessage name="priority" component="div" className="text-red-500 text-sm mt-1" /&amp;gt;
                    &amp;lt;/div&amp;gt;

                    &amp;lt;div&amp;gt;
                        &amp;lt;label htmlFor="status" className="block text-sm font-medium text-gray-700"&amp;gt;Status&amp;lt;/label&amp;gt;
                        &amp;lt;Field
                            as="select"
                            name="status"
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                        &amp;gt;
                            &amp;lt;option value="pending"&amp;gt;Pending&amp;lt;/option&amp;gt;
                            &amp;lt;option value="completed"&amp;gt;Completed&amp;lt;/option&amp;gt;
                        &amp;lt;/Field&amp;gt;
                        &amp;lt;ErrorMessage name="status" component="div" className="text-red-500 text-sm mt-1" /&amp;gt;
                    &amp;lt;/div&amp;gt;

                    &amp;lt;button
                        type="submit"
                        disabled={isSubmitting}
                        className="w-full bg-indigo-600 text-white py-2 px-4 rounded-md hover:bg-indigo-700 disabled:bg-indigo-400"
                    &amp;gt;
                        {isUpdate ? 'Update' : 'Create'} Todo
                    &amp;lt;/button&amp;gt;
                &amp;lt;/Form&amp;gt;
            )}
        &amp;lt;/Formik&amp;gt;
    );
};

export default TodoForm;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;components/second/TodoList.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// TodoList.jsx
import React, { useState, useEffect } from 'react';
import API from '../../utils/axios';
import TodoForm from './TodoForm';
import { useAuth } from '../../provider/authProvider';
import { useNavigate } from 'react-router-dom';

const TodoList = () =&amp;gt; {
    const { setToken } = useAuth();
    const navigate = useNavigate();



    const [todos, setTodos] = useState([]);
    const [showUpdateModal, setShowUpdateModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [selectedTodo, setSelectedTodo] = useState(null);

    useEffect(() =&amp;gt; {
        fetchTodos();
    }, []);

    const fetchTodos = async () =&amp;gt; {
        try {
            const response = await API.get('/todos');
            setTodos(response.data);
        } catch (error) {
            console.error('Error fetching todos:', error);
        }
    };

    const handleDeleteClick = (todo) =&amp;gt; {
        setSelectedTodo(todo);
        setShowDeleteModal(true);
    };

    const handleUpdateClick = (todo) =&amp;gt; {
        setSelectedTodo(todo);
        setShowUpdateModal(true);
    };

    const handleDelete = async () =&amp;gt; {
        try {
            await API.delete(`/todos/${selectedTodo._id}`);
            setTodos(todos.filter(todo =&amp;gt; todo._id !== selectedTodo._id));
            setShowDeleteModal(false);
        } catch (error) {
            console.error('Error deleting todo:', error);
        }
    };

    const handleLogout = () =&amp;gt; {
        setToken();
        navigate("/", { replace: true });
    };

    return (
        &amp;lt;div className="container mx-auto mt-8 px-4"&amp;gt;
            &amp;lt;button className='p-2 bg-gray-600 text-white cursor-pointer' onClick={handleLogout}&amp;gt;Logout&amp;lt;/button&amp;gt;
            &amp;lt;h2 className="text-2xl font-bold mb-4"&amp;gt;Todo List&amp;lt;/h2&amp;gt;
            &amp;lt;TodoForm fetchTodos={fetchTodos} /&amp;gt;

            &amp;lt;div className="mt-6 overflow-x-auto"&amp;gt;
                &amp;lt;table className="w-full border-collapse"&amp;gt;
                    &amp;lt;thead&amp;gt;
                        &amp;lt;tr className="bg-gray-100"&amp;gt;
                            &amp;lt;th className="p-3 text-left"&amp;gt;Title&amp;lt;/th&amp;gt;
                            &amp;lt;th className="p-3 text-left"&amp;gt;Description&amp;lt;/th&amp;gt;
                            &amp;lt;th className="p-3 text-left"&amp;gt;Due Date&amp;lt;/th&amp;gt;
                            &amp;lt;th className="p-3 text-left"&amp;gt;Priority&amp;lt;/th&amp;gt;
                            &amp;lt;th className="p-3 text-left"&amp;gt;Status&amp;lt;/th&amp;gt;
                            &amp;lt;th className="p-3 text-left"&amp;gt;Actions&amp;lt;/th&amp;gt;
                        &amp;lt;/tr&amp;gt;
                    &amp;lt;/thead&amp;gt;
                    &amp;lt;tbody&amp;gt;
                        {todos.map(todo =&amp;gt; (
                            &amp;lt;tr key={todo._id} className="border-b hover:bg-gray-50"&amp;gt;
                                &amp;lt;td className="p-3"&amp;gt;{todo.title}&amp;lt;/td&amp;gt;
                                &amp;lt;td className="p-3"&amp;gt;{todo.description}&amp;lt;/td&amp;gt;
                                &amp;lt;td className="p-3"&amp;gt;{new Date(todo.dueDate).toLocaleDateString()}&amp;lt;/td&amp;gt;
                                &amp;lt;td className="p-3"&amp;gt;
                                    &amp;lt;span className={`px-2 py-1 rounded capitalize ${todo.priority === 'high' ? 'bg-red-100 text-red-800' :
                                        todo.priority === 'medium' ? 'bg-yellow-100 text-yellow-800' :
                                            'bg-green-100 text-green-800'
                                        }`}&amp;gt;
                                        {todo.priority}
                                    &amp;lt;/span&amp;gt;
                                &amp;lt;/td&amp;gt;
                                &amp;lt;td className="p-3"&amp;gt;
                                    &amp;lt;span className={`px-2 py-1 rounded capitalize ${todo.status === 'completed' ? 'bg-green-100 text-green-800' :
                                        todo.status === 'in-progress' ? 'bg-blue-100 text-blue-800' :
                                            'bg-gray-100 text-gray-800'
                                        }`}&amp;gt;
                                        {todo.status}
                                    &amp;lt;/span&amp;gt;
                                &amp;lt;/td&amp;gt;
                                &amp;lt;td className="p-3"&amp;gt;
                                    &amp;lt;button
                                        onClick={() =&amp;gt; handleUpdateClick(todo)}
                                        className="bg-yellow-500 text-white px-3 py-1 rounded mr-2 hover:bg-yellow-600"
                                    &amp;gt;
                                        Edit
                                    &amp;lt;/button&amp;gt;
                                    &amp;lt;button
                                        onClick={() =&amp;gt; handleDeleteClick(todo)}
                                        className="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600"
                                    &amp;gt;
                                        Delete
                                    &amp;lt;/button&amp;gt;
                                &amp;lt;/td&amp;gt;
                            &amp;lt;/tr&amp;gt;
                        ))}
                    &amp;lt;/tbody&amp;gt;
                &amp;lt;/table&amp;gt;
            &amp;lt;/div&amp;gt;

            {showUpdateModal &amp;amp;&amp;amp; (
                &amp;lt;div className="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center"&amp;gt;
                    &amp;lt;div className="bg-white p-6 rounded-lg w-full max-w-md"&amp;gt;
                        &amp;lt;div className="flex justify-between items-center mb-4"&amp;gt;
                            &amp;lt;h3 className="text-xl font-bold"&amp;gt;Update Todo&amp;lt;/h3&amp;gt;
                            &amp;lt;button onClick={() =&amp;gt; setShowUpdateModal(false)} className="text-gray-500 hover:text-gray-700"&amp;gt;
                                ×
                            &amp;lt;/button&amp;gt;
                        &amp;lt;/div&amp;gt;
                        &amp;lt;TodoForm
                            fetchTodos={fetchTodos}
                            todo={selectedTodo}
                            isUpdate={true}
                            closeModal={() =&amp;gt; setShowUpdateModal(false)}
                        /&amp;gt;
                    &amp;lt;/div&amp;gt;
                &amp;lt;/div&amp;gt;
            )}

            {showDeleteModal &amp;amp;&amp;amp; (
                &amp;lt;div className="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center"&amp;gt;
                    &amp;lt;div className="bg-white p-6 rounded-lg w-full max-w-md"&amp;gt;
                        &amp;lt;h3 className="text-xl font-bold mb-4"&amp;gt;Confirm Delete&amp;lt;/h3&amp;gt;
                        &amp;lt;p className="mb-4"&amp;gt;Are you sure you want to delete "{selectedTodo?.title}"?&amp;lt;/p&amp;gt;
                        &amp;lt;div className="flex justify-end gap-2"&amp;gt;
                            &amp;lt;button
                                onClick={() =&amp;gt; setShowDeleteModal(false)}
                                className="bg-gray-300 px-4 py-2 rounded hover:bg-gray-400"
                            &amp;gt;
                                Cancel
                            &amp;lt;/button&amp;gt;
                            &amp;lt;button
                                onClick={handleDelete}
                                className="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600"
                            &amp;gt;
                                Delete
                            &amp;lt;/button&amp;gt;
                        &amp;lt;/div&amp;gt;
                    &amp;lt;/div&amp;gt;
                &amp;lt;/div&amp;gt;
            )}
        &amp;lt;/div&amp;gt;
    );
};

export default TodoList;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Auth Protected Route example</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Fri, 04 Apr 2025 04:12:00 +0000</pubDate>
      <link>https://dev.to/codelover405/auth-2jg2</link>
      <guid>https://dev.to/codelover405/auth-2jg2</guid>
      <description>&lt;p&gt;app.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import AuthProvider from "./provider/authProvider";
import Routes from "./routes";

function App() {
  return (
    &amp;lt;AuthProvider&amp;gt;
      &amp;lt;Routes /&amp;gt;
    &amp;lt;/AuthProvider&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;provider/authProvider.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from "axios";
import { createContext, useContext, useEffect, useMemo, useState } from "react";

const AuthContext = createContext();

const AuthProvider = ({ children }) =&amp;gt; {
  // State to hold the authentication token
  const [token, setToken_] = useState(localStorage.getItem("token"));

  // Function to set the authentication token
  const setToken = (newToken) =&amp;gt; {
    setToken_(newToken);
  };

  useEffect(() =&amp;gt; {
    if (token) {
      axios.defaults.headers.common["Authorization"] = "Bearer " + token;
      localStorage.setItem("token", token);
    } else {
      delete axios.defaults.headers.common["Authorization"];
      localStorage.removeItem("token");
    }
  }, [token]);

  // Memoized value of the authentication context
  const contextValue = useMemo(
    () =&amp;gt; ({
      token,
      setToken,
    }),
    [token]
  );

  // Provide the authentication context to the children components
  return (
    &amp;lt;AuthContext.Provider value={contextValue}&amp;gt;{children}&amp;lt;/AuthContext.Provider&amp;gt;
  );
};

export const useAuth = () =&amp;gt; {
  return useContext(AuthContext);
};

export default AuthProvider;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;routes/ProtectedRoute.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "../provider/authProvider";

export const ProtectedRoute = () =&amp;gt; {
  const { token } = useAuth();

  // Check if the user is authenticated
  if (!token) {
    // If not authenticated, redirect to the login page
    return &amp;lt;Navigate to="/login" /&amp;gt;;
  }

  // If authenticated, render the child routes
  return &amp;lt;Outlet /&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;routes/index.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { useAuth } from "../provider/authProvider";
import { ProtectedRoute } from "./ProtectedRoute";
import Login from "../pages/Login";
import Logout from "../pages/Logout";

const Routes = () =&amp;gt; {
  const { token } = useAuth();

  // Define public routes accessible to all users
  const routesForPublic = [
    {
      path: "/service",
      element: &amp;lt;div&amp;gt;Service Page&amp;lt;/div&amp;gt;,
    },
    {
      path: "/about-us",
      element: &amp;lt;div&amp;gt;About Us&amp;lt;/div&amp;gt;,
    },
  ];

  // Define routes accessible only to authenticated users
  const routesForAuthenticatedOnly = [
    {
      path: "/",
      element: &amp;lt;ProtectedRoute /&amp;gt;, // Wrap the component in ProtectedRoute
      children: [
        {
          path: "",
          element: &amp;lt;div&amp;gt;User Home Page&amp;lt;/div&amp;gt;,
        },
        {
          path: "/profile",
          element: &amp;lt;div&amp;gt;User Profile&amp;lt;/div&amp;gt;,
        },
        {
          path: "/logout",
          element: &amp;lt;Logout/&amp;gt;,
        },
      ],
    },
  ];

  // Define routes accessible only to non-authenticated users
  const routesForNotAuthenticatedOnly = [
    {
      path: "/",
      element: &amp;lt;div&amp;gt;Home Page&amp;lt;/div&amp;gt;,
    },
    {
      path: "/login",
      element: &amp;lt;Login/&amp;gt;,
    },
  ];

  // Combine and conditionally include routes based on authentication status
  const router = createBrowserRouter([
    ...routesForPublic,
    ...(!token ? routesForNotAuthenticatedOnly : []),
    ...routesForAuthenticatedOnly,
  ]);

  // Provide the router configuration using RouterProvider
  return &amp;lt;RouterProvider router={router} /&amp;gt;;
};

export default Routes;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;pages/login.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useNavigate } from "react-router-dom";
import { useAuth } from "../provider/authProvider";

const Login = () =&amp;gt; {
  const { setToken } = useAuth();
  const navigate = useNavigate();

  const handleLogin = () =&amp;gt; {
    setToken("this is a test token");
    navigate("/", { replace: true });
  };

  setTimeout(() =&amp;gt; {
    handleLogin();
  }, 3 * 1000);

  return &amp;lt;&amp;gt;Login Page&amp;lt;/&amp;gt;;
};

export default Login;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;pages/Logout.jsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useNavigate } from "react-router-dom";
import { useAuth } from "../provider/authProvider";

const Logout = () =&amp;gt; {
  const { setToken } = useAuth();
  const navigate = useNavigate();

  const handleLogout = () =&amp;gt; {
    setToken();
    navigate("/", { replace: true });
  };

  setTimeout(() =&amp;gt; {
    handleLogout();
  }, 3 * 1000);

  return &amp;lt;&amp;gt;Logout Page&amp;lt;/&amp;gt;;
};

export default Logout;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; "dependencies": {
    "axios": "^1.4.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.11.2"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;&lt;br&gt;
https://github.com/sanjay-arya/react-auth-demo&lt;br&gt;
https://github.com/UtsavMavani2/react-auth-demo&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Create a square radio button</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Sat, 04 Nov 2023 11:57:44 +0000</pubDate>
      <link>https://dev.to/codelover405/create-a-square-radio-button-15fi</link>
      <guid>https://dev.to/codelover405/create-a-square-radio-button-15fi</guid>
      <description>&lt;p&gt;To create a &lt;strong&gt;square radio button&lt;/strong&gt; with a value inside, you can use HTML and CSS. Here's an example of how you can achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;style&amp;gt;
    /* Style for the radio button container */
    .radio-container {
      display: inline-block;
      position: relative;
      padding-left: 30px; /* Adjust the size of the square */
    }

    /* Style for the radio button input */
    .radio-container input[type="radio"] {
      position: absolute;
      opacity: 0;
      cursor: pointer;
    }

    /* Style for the radio button label (the square) */
    .radio-container .radio-square {
      position: absolute;
      top: 0;
      left: 0;
      width: 20px; /* Adjust the size of the square */
      height: 20px; /* Adjust the size of the square */
      background-color: #3498db; /* Color of the square */
      border: 1px solid #3498db; /* Border around the square */
    }

    /* Style for the value inside the square */
    .radio-container .radio-value {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: white; /* Color of the text */
    }

    /* Style for the radio button label when selected */
    .radio-container input[type="radio"]:checked + .radio-square {
      background-color: #e74c3c; /* Change the color when selected */
    }
  &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;label class="radio-container"&amp;gt;
    &amp;lt;input type="radio" name="myRadioButton" value="A"&amp;gt;
    &amp;lt;span class="radio-square"&amp;gt;
      &amp;lt;span class="radio-value"&amp;gt;A&amp;lt;/span&amp;gt;
    &amp;lt;/span&amp;gt;
  &amp;lt;/label&amp;gt;

  &amp;lt;label class="radio-container"&amp;gt;
    &amp;lt;input type="radio" name="myRadioButton" value="B"&amp;gt;
    &amp;lt;span class="radio-square"&amp;gt;
      &amp;lt;span class="radio-value"&amp;gt;B&amp;lt;/span&amp;gt;
    &amp;lt;/span&amp;gt;
  &amp;lt;/label&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we create a &lt;strong&gt;custom radio&lt;/strong&gt; button using a label element that wraps an input of type "radio." We style the radio button using CSS. You can adjust the size of the square and its color as needed. The value inside the square is specified within the radio-value class. The example shows two radio buttons with values "A" and "B," but you can add more as needed.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>html</category>
      <category>css</category>
    </item>
    <item>
      <title>React.js make custom Carousel with image inside Next ,Previous button and thumbnail image</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Wed, 18 Oct 2023 06:52:14 +0000</pubDate>
      <link>https://dev.to/codelover405/reactjs-make-custom-carousel-with-image-inside-next-previous-button-and-thumbnail-image-4fg7</link>
      <guid>https://dev.to/codelover405/reactjs-make-custom-carousel-with-image-inside-next-previous-button-and-thumbnail-image-4fg7</guid>
      <description>&lt;p&gt;To implement the &lt;strong&gt;nextImage&lt;/strong&gt;, &lt;strong&gt;prevImage&lt;/strong&gt;, and &lt;strong&gt;selectImage&lt;/strong&gt; logic, you can use state to keep track of the current image index and update it accordingly. Here's how you can modify the Carousel component to include these functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import bike from "../src/assert/images/grid-list/bike.jpg";
import breakfast from "../src/assert/images/grid-list/breakfast.jpg";
import camera from "../src/assert/images/grid-list/camera.jpg";
import honey from "../src/assert/images/grid-list/honey.jpg";
import "./Carousel.css ";

//import image
const images = [bike,breakfast,camera,honey]; 
const CarouselProviders = () =&amp;gt; {
    const [currentImageIndex, setCurrentImageIndex] = useState(0);

    const nextImage = () =&amp;gt; {
        setCurrentImageIndex((prevIndex) =&amp;gt;
          prevIndex === images.length - 1 ? 0 : prevIndex + 1
        );
      };

      const prevImage = () =&amp;gt; {
        setCurrentImageIndex((prevIndex) =&amp;gt;
          prevIndex === 0 ? images.length - 1 : prevIndex - 1
        );
      };

      const selectImage = (index) =&amp;gt; {
        setCurrentImageIndex(index);
      };

  return (
    &amp;lt;div&amp;gt;
      {/* &amp;lt;div className="carousel-container"&amp;gt;
      &amp;lt;div className="carousel"&amp;gt;
        &amp;lt;div className="carousel-image"&amp;gt;
          &amp;lt;img src={images[currentImageIndex]} alt={`Image ${currentImageIndex}`} /&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div className="carousel-controls"&amp;gt;
          &amp;lt;button onClick={prevImage}&amp;gt;Previous&amp;lt;/button&amp;gt;
          &amp;lt;button onClick={nextImage}&amp;gt;Next&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div className="thumbnail-container"&amp;gt;
        {images.map((image, index) =&amp;gt; (
          &amp;lt;img
            key={index}
            src={image}
            alt={`Thumbnail ${index}`}
            className={index === currentImageIndex ? 'active' : ''}
            onClick={() =&amp;gt; selectImage(index)}
          /&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt; */}

&amp;lt;div className="carousel-container"&amp;gt;
&amp;lt;div className="carousel"&amp;gt;
      &amp;lt;div className="carousel-image"&amp;gt;
        &amp;lt;img src={images[currentImageIndex]} alt={`Image ${currentImageIndex}`} /&amp;gt;
        &amp;lt;div className="carousel-controls"&amp;gt;
          &amp;lt;button className="prev" onClick={prevImage}&amp;gt;Previous&amp;lt;/button&amp;gt;
          &amp;lt;button className="next" onClick={nextImage}&amp;gt;Next&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div className="thumbnail-container"&amp;gt;
        {images.map((image, index) =&amp;gt; (
          &amp;lt;img
            key={index}
            src={image}
            alt={`Thumbnail ${index}`}
            className={index === currentImageIndex ? 'active' : ''}
            onClick={() =&amp;gt; selectImage(index)}
          /&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default CarouselProviders

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, the &lt;strong&gt;nextImage&lt;/strong&gt; function increments the image index, and if it reaches the end of the images array, it loops back to the first image. The &lt;strong&gt;prevImage&lt;/strong&gt; function decrements the image index and, if it reaches the first image, it loops back to the last image. The &lt;strong&gt;selectImage&lt;/strong&gt; function sets the current image index to the selected thumbnail index.&lt;/p&gt;

&lt;p&gt;Make css &lt;strong&gt;Carouse.css&lt;/strong&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.carousel-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.carousel {
  display: flex;
  align-items: center;
  /* width: 80%; */
  position: relative;
}

.carousel-image {
  /* width: 70%; */
  display: flex;
  justify-content: center;
  position: relative;
}

.carousel-image img {
  max-width: 100%;
  transition: transform 0.3s ease-in-out;
}

.carousel-controls {
  display: flex;
  justify-content: space-between;
  width: 100%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.carousel-controls button {
  background-color: #333;
  color: #fff;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

.carousel-controls .prev {
  left: 0;
}

.carousel-controls .next {
  right: 0;
}

.thumbnail-container {
  display: flex;
  justify-content: center;
  width: 80%;
  margin-top: 20px;
}

.thumbnail-container img {
  width: 60px;
  height: 40px;
  margin: 0 10px;
  cursor: pointer;
}

.active {
  border: 2px solid #333;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>carousel</category>
    </item>
    <item>
      <title>ReactJS to fetch weather data from a weather API</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Wed, 04 Oct 2023 11:52:24 +0000</pubDate>
      <link>https://dev.to/codelover405/reactjs-to-fetch-weather-data-from-a-weather-api-3ela</link>
      <guid>https://dev.to/codelover405/reactjs-to-fetch-weather-data-from-a-weather-api-3ela</guid>
      <description>&lt;p&gt;ReactJS to fetch weather data from a weather API based on the user's location. In this example, we'll use the OpenWeatherMap API to get weather information. You'll need to sign up for an API key from OpenWeatherMap to use their service.&lt;/p&gt;

&lt;p&gt;Here's a simple implementation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Create a new React app&lt;/strong&gt; (if you don't have one already) using &lt;strong&gt;create-react-app&lt;/strong&gt; or your preferred method.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Install the necessary dependencies:&lt;/strong&gt;
You'll need to install the axios library to make API requests. You can install it using:
&lt;code&gt;npm install axios
&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Create a Weather component:&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Create a new component, let's call it Weather.js. This component will handle fetching weather data and displaying it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useEffect } from 'react';
import axios from 'axios';

const Weather = () =&amp;gt; {
  const [weatherData, setWeatherData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() =&amp;gt; {
    // Function to fetch weather data
    const fetchWeatherData = async () =&amp;gt; {
      try {
        // Get user's location using the browser's geolocation API
        navigator.geolocation.getCurrentPosition(async (position) =&amp;gt; {
          const { latitude, longitude } = position.coords;

          // Replace 'YOUR_API_KEY' with your actual OpenWeatherMap API key
          const apiKey = 'YOUR_API_KEY';
          const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&amp;amp;lon=${longitude}&amp;amp;appid=${apiKey}&amp;amp;units=metric`;

          const response = await axios.get(apiUrl);
          setWeatherData(response.data);
          setLoading(false);
        });
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchWeatherData();
  }, []);

  if (loading) {
    return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
  }

  if (error) {
    return &amp;lt;div&amp;gt;Error: {error.message}&amp;lt;/div&amp;gt;;
  }

  if (!weatherData) {
    return &amp;lt;div&amp;gt;No weather data available.&amp;lt;/div&amp;gt;;
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Weather Information&amp;lt;/h1&amp;gt;
      &amp;lt;p&amp;gt;Location: {weatherData.name}, {weatherData.sys.country}&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;Temperature: {weatherData.main.temp}°C&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;Weather: {weatherData.weather[0].description}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Weather;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Use the Weather component:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import Weather from './Weather';

function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;Weather /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember to replace &lt;strong&gt;'YOUR_API_KEY'&lt;/strong&gt; with your actual OpenWeatherMap API key in the Weather.js file.&lt;/p&gt;

&lt;p&gt;This example demonstrates how to fetch weather data using the user's location. However, keep in mind that using the browser's geolocation API might prompt the user for permission to access their location.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>weather</category>
      <category>react</category>
    </item>
    <item>
      <title>Tab based login and signup logic in React.js</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Wed, 04 Oct 2023 11:42:53 +0000</pubDate>
      <link>https://dev.to/codelover405/tab-based-login-and-signup-logic-in-reactjs-5f6</link>
      <guid>https://dev.to/codelover405/tab-based-login-and-signup-logic-in-reactjs-5f6</guid>
      <description>&lt;p&gt;&lt;em&gt;To implement a tab-based login and signup logic using React.js, you can follow these steps:&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Setup Your Project:&lt;/strong&gt;
Make sure you have a React.js project set up. You can create one using Create React App or any other method you prefer
.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Component Structure:&lt;/strong&gt;
Create a component structure that includes a parent component for the tabs and two child components for the login and signup forms.&lt;/li&gt;
&lt;li&gt; State Management:
Use React state to manage the active tab and the content to be displayed.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Tab Component:&lt;/strong&gt;
Create a component for the tabs that will allow users to switch between the login and signup forms.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Login and Signup Components:&lt;/strong&gt;
Create separate components for the login and signup forms. These components will render the necessary input fields and buttons.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Handling Tab Change:&lt;/strong&gt;
Implement a function to handle tab changes. This function should update the active tab in the component's state.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Conditional Rendering:&lt;/strong&gt;
Use the active tab state to conditionally render the login or signup form components.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here's a basic example of how you could structure your code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import LoginForm from './LoginForm';
import SignupForm from './SignupForm';

function TabChangeLoginSignup() {
  const [activeTab, setActiveTab] = useState('login'); // Initial tab is 'login'

  const handleTabChange = (tab) =&amp;gt; {
    setActiveTab(tab);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;button onClick={() =&amp;gt; handleTabChange('login')}&amp;gt;Login&amp;lt;/button&amp;gt;
        &amp;lt;button onClick={() =&amp;gt; handleTabChange('signup')}&amp;gt;Signup&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        {activeTab === 'login' ? &amp;lt;LoginForm /&amp;gt; : &amp;lt;SignupForm /&amp;gt;}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default TabChangeLoginSignup;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, you'd need to create &lt;strong&gt;LoginForm.js&lt;/strong&gt; and &lt;strong&gt;SignupForm.js&lt;/strong&gt; components that render the actual forms. These components will handle form input, validation, and submission.&lt;/p&gt;

&lt;p&gt;Remember that this is a basic example. You can enhance it by adding form validation, error handling, and styling as needed. Also, consider using a state management library like Redux or context API if your application grows more complex.&lt;/p&gt;

</description>
      <category>react</category>
      <category>tab</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>Custom Modal React.js</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Wed, 04 Oct 2023 11:24:35 +0000</pubDate>
      <link>https://dev.to/codelover405/custom-modal-reactjs-if1</link>
      <guid>https://dev.to/codelover405/custom-modal-reactjs-if1</guid>
      <description>&lt;h2&gt;
  
  
  Exmaple-1:
&lt;/h2&gt;

&lt;p&gt;To create a reusable and responsive custom &lt;strong&gt;modal&lt;/strong&gt; in React.js that centers on screens with a minimum width of 768px and is positioned at the top 5% otherwise, you can follow these steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Set up a new React project or use an existing one.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a new component for your modal. You can name it &lt;strong&gt;CustomModal.js.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// CustomModal.js
import React from 'react';
import './CustomModal.css';

const CustomModal = ({ isOpen, onClose, children }) =&amp;gt; {
  if (!isOpen) return null;

  return (
    &amp;lt;div className="custom-modal"&amp;gt;
      &amp;lt;div className="custom-modal-content"&amp;gt;
        &amp;lt;button className="close-button" onClick={onClose}&amp;gt;
          Close
        &amp;lt;/button&amp;gt;
        {children}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default CustomModal;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a CSS file for your modal styles. You can name it &lt;strong&gt;CustomModal.css&lt;/strong&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* CustomModal.css */
.custom-modal {
  position: fixed;
  top: 5%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  overflow: auto;
}

@media (min-width: 768px) {
  .custom-modal {
    top: 50%;
    transform: translate(-50%, -50%);
  }
}

.custom-modal-content {
  background: #fff;
  padding: 20px;
  border-radius: 5px;
  position: relative;
  max-width: 80%;
  width: 400px;
  max-height: 80%;
  overflow-y: auto;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background: none;
  border: none;
  cursor: pointer;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a parent component (e.g., &lt;strong&gt;App.js&lt;/strong&gt;) where you'll use the CustomModal component.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.js
import React, { useState } from 'react';
import CustomModal from './CustomModal';

function App() {
  const [modalIsOpen, setModalIsOpen] = useState(false);

  const openModal = () =&amp;gt; {
    setModalIsOpen(true);
  };

  const closeModal = () =&amp;gt; {
    setModalIsOpen(false);
  };

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;button onClick={openModal}&amp;gt;Open Modal&amp;lt;/button&amp;gt;
      &amp;lt;CustomModal isOpen={modalIsOpen} onClose={closeModal}&amp;gt;
        &amp;lt;h2&amp;gt;Modal Content&amp;lt;/h2&amp;gt;
        &amp;lt;p&amp;gt;This is a reusable custom modal.&amp;lt;/p&amp;gt;
      &amp;lt;/CustomModal&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Now you have a responsive and reusable custom modal that centers on screens with a minimum width of 768px and is positioned at the top 5% for smaller screens. The  you can close the modal by clicking the "Close" button or pressing the Escape key.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>beginners</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Google Translate API in a React.js</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Mon, 02 Oct 2023 04:01:05 +0000</pubDate>
      <link>https://dev.to/codelover405/google-translate-api-in-a-reactjs-2697</link>
      <guid>https://dev.to/codelover405/google-translate-api-in-a-reactjs-2697</guid>
      <description>&lt;p&gt;Google Translate API in a React.js application to translate text between languages, you can follow these steps:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Set Up Google Cloud Project:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go to the Google Cloud Console (&lt;a href="https://console.cloud.google.com/" rel="noopener noreferrer"&gt;https://console.cloud.google.com/&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;Create a new project or use an existing one.&lt;/li&gt;
&lt;li&gt;Enable the "Cloud Translation API" for your project.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Obtain API Key:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In the Cloud Console, navigate to "APIs &amp;amp; Services" &amp;gt; "Credentials."&lt;/li&gt;
&lt;li&gt;Create a new API Key.&lt;/li&gt;
&lt;li&gt;Keep this API Key handy as you'll need it to make API requests.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Install Dependencies:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Open your React.js project's terminal and install the necessary packages:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install axios
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Create API Request:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new file, e.g., GoogleTranslate.js, to handle API requests.&lt;/li&gt;
&lt;li&gt;Inside this file, you can use Axios to send requests to the Google Translate API:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from 'axios';

const API_KEY = 'YOUR_GOOGLE_TRANSLATE_API_KEY';
const API_URL = 'https://translation.googleapis.com/language/translate/v2';

const translateText = async (text, targetLanguage) =&amp;gt; {
  const response = await axios.post(
    `${API_URL}?key=${API_KEY}`,
    {
      q: text,
      target: targetLanguage,
    }
  );

  return response.data.data.translations[0].translatedText;
};

export default translateText;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Integrate into React Component:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Now you can use the translateText function in your React components.&lt;/li&gt;
&lt;li&gt;Let's assume you have an input field for the text and a dropdown to select the target language.&lt;/li&gt;
&lt;li&gt;When the user enters text and selects a language, you can trigger the translation:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import translateText from './GoogleTranslate';

function App() {
  const [inputText, setInputText] = useState('');
  const [targetLanguage, setTargetLanguage] = useState('es'); // Default: Spanish

  const handleTranslate = async () =&amp;gt; {
    if (inputText) {
      const translatedText = await translateText(inputText, targetLanguage);
      // Do something with the translatedText, e.g., display it on the page.
    }
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input
        type="text"
        value={inputText}
        onChange={(e) =&amp;gt; setInputText(e.target.value)}
      /&amp;gt;
      &amp;lt;select
        value={targetLanguage}
        onChange={(e) =&amp;gt; setTargetLanguage(e.target.value)}
      &amp;gt;
        &amp;lt;option value="es"&amp;gt;Spanish&amp;lt;/option&amp;gt;
        &amp;lt;option value="fr"&amp;gt;French&amp;lt;/option&amp;gt;
        {/* Add more language options */}
      &amp;lt;/select&amp;gt;
      &amp;lt;button onClick={handleTranslate}&amp;gt;Translate&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember to replace '&lt;strong&gt;&lt;em&gt;YOUR_GOOGLE_TRANSLATE_API_KEY&lt;/em&gt;&lt;/strong&gt;' with your actual API Key in the GoogleTranslate.js file.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>javascript</category>
      <category>translate</category>
    </item>
    <item>
      <title>css image inside center class</title>
      <dc:creator>code lover</dc:creator>
      <pubDate>Fri, 09 Jun 2023 07:26:19 +0000</pubDate>
      <link>https://dev.to/codelover405/css-image-inside-center-class-2ol</link>
      <guid>https://dev.to/codelover405/css-image-inside-center-class-2ol</guid>
      <description>&lt;p&gt;&lt;code&gt;span {&lt;br&gt;
  position: absolute;&lt;br&gt;
  top: 50%;&lt;br&gt;
  left: 50%;&lt;br&gt;
  transform: translate(-50%, -50%);&lt;br&gt;
 }&lt;/code&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
