114 lines
3 KiB
TypeScript
114 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";
|
|
import Config from "../../config"
|
|
|
|
export default function URLShortener() {
|
|
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 config = Config()
|
|
const api_endpoint = "/api/v1/shorten";
|
|
|
|
const api_url = `${config.url}${api_endpoint}`;
|
|
|
|
// Send the POST request to the backend
|
|
await axios
|
|
.post(api_url , {
|
|
url: url
|
|
})
|
|
.then((response) => {
|
|
if (response) {
|
|
const shortUrl: string = response.data.url;
|
|
setShortenedUrl(shortUrl);
|
|
setShowInput(true);
|
|
}
|
|
});
|
|
|
|
setTimeout(() => {
|
|
setShowInput(false);
|
|
}, 10000);
|
|
} 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>
|
|
);
|
|
}
|