shortenit/frontend/src/components/URLShortener/URLShortener.tsx
2024-12-25 22:35:20 +01:00

112 lines
3 KiB
TypeScript

import React, { useState } from "react";
import "./URLShortener.css";
import axios from "axios";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
export default function () {
const [url, setUrl] = useState<string>("");
const [shortenedUrl, setShortenedUrl] = useState<string>("");
const [showInput, setShowInput] = useState<boolean>(false);
async function ShortenIt(e: React.FormEvent) {
e.preventDefault();
if (!url) {
toast.error("Please provide a URL", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "dark",
className: "custom-toast",
});
return;
}
try {
const timestamp = Math.floor(Date.now() / 1000);
// Send the POST request to the backend
await axios
.post("http://127.0.0.1:8000/shortenit", {
url: url,
timestamp: timestamp,
})
.then((response) => {
if (response) {
const code: string = response.data.url;
const fullShortenedUrl: string = `http://127.0.0.1:8000/${code}`;
setShortenedUrl(fullShortenedUrl);
setShowInput(true);
}
});
setTimeout(() => {
setShowInput(false);
}, 900000);
} catch (error) {
console.log(error);
}
}
async function copyURL() {
try {
if (shortenedUrl) {
await navigator.clipboard.writeText(shortenedUrl);
toast.success("Copied to Clipboard", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "dark",
className: "custom-toast",
});
}
} catch (error) {
console.log(error);
}
}
return (
<div className="URLShortener-component">
<div className="left-side">
<h1>Paste the URL</h1>
<form className="url-input" onSubmit={ShortenIt}>
<input
type="text"
placeholder="www.example.com"
aria-label="URL input field"
value={url}
onChange={(e) => setUrl(e.target.value)}
/>
<button type="submit">Shorten It</button>
</form>
{shortenedUrl && showInput && (
<div className="url-input shortened">
<input type="text" readOnly value={shortenedUrl} />
<button onClick={copyURL}>Copy</button>
</div>
)}
</div>
<div className="right-side">
<div className="right-side-title">
<h1>Shorten It</h1>
</div>
<div className="right-side-content">
<p>
Shortenit is a free and open-source URL shortening service designed
for simplicity and efficiency.
</p>
</div>
</div>
<ToastContainer />
</div>
);
}