Advertisement

Responsive Advertisement

Simply Data Store in Local Storage

 

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

const AddData = () => {
  const navigate = useNavigate();
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [image, setImage] = useState(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    const existingData = JSON.parse(localStorage.getItem("data")) || [];

    const newEntry = {
      id: Date.now(),
      title,
      description,
      image,
    };

    const updatedData = [...existingData, newEntry];
    localStorage.setItem("data", JSON.stringify(updatedData));

    alert("Data submitted successfully!");

    navigate("/");
  };

  return (
    <div className="p-5">
      <h1 className="font-bold text-3xl">Add Data</h1>
      <form action="#" className="w-1/3" onSubmit={handleSubmit}>
        <div className="flex flex-col gap-1">
          <label htmlFor="title">Title</label>
          <input
            type="text"
            name="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Enter your title"
            className="border-2 border-gray-300"
          />
        </div>
        <div className="flex flex-col gap-1 mt-3">
          <label htmlFor="description">Description</label>
          <textarea
            name="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Enter project description"
            className="border-2 border-gray-300"
          />
        </div>
        <div className="flex flex-col gap-1 mt-3">
          <label htmlFor="banner">Banner</label>
          <input
            type="file"
            onChange={(e) => setImage(URL.createObjectURL(e.target.files[0]))}
            className=""
          />
        </div>
        <button
          type="submit"
          className="px-4 py-1 bg-green-500 rounded-md mt-5"
        >
          Submit
        </button>
      </form>
    </div>
  );
};

export default AddData;

Post a Comment

0 Comments