UpdateGadh

UPDATEGADH.COM

Unbelievable! How to Build a URL Shortener in React with Shrtcode

Create Your Own Viral URL Shortener in React with Shrtcode – How to Build a URL Shortener in React with Shrtcode

“How Does URL Shortening Work ?”

The method of URL shortening entails encoding the original link and assigning it a shorter, random character sequence that is recorded in a database. When a user clicks on the shortened URL, the server uses this random sequence to get the original link and redirects the user to it. This approach, of course, demands the creation of a backend system.

YouTube player

We will use the capabilities of the Shrtcode API in this guide to streamline this functionality, avoiding the need for us to delve into the subtleties of backend operations.”

How to Build a URL Shortener

As acclaimed author Michael Lewis, known for his work on “Moneyball,” wisely remarked, “There’s something unfavorable in every advantage and something advantageous in every drawback.” Let’s delve into the merits and demerits of URL shorteners.

Pros, How to Build a URL Shortener:

  1. Facilitate Sharing: URL shorteners simplify the sharing process. They reduce the length of URLs, making it more convenient for users to copy, paste, or share them, particularly in situations where character limits apply, such as messaging apps or printed materials.
  2. User-Friendly URLs: Most URL shorteners offer the option to create custom links, replacing long and cryptic URLs with concise, intuitive, and memorable addresses. This customization enhances user experience and aids in brand recognition.
  3. Analytics Insights: Many URL shortening services provide analytics features, enabling users to track link performance. This data includes valuable information on click-through rates and traffic sources, empowering businesses to refine their content distribution strategies.

Cons ,How to Build a URL Shortener:

  1. Risk of Dead Links: URL shorteners are susceptible to the stability of the server used to create the shortened links. If the server experiences downtime or ceases to function, all associated links become inactive, potentially causing frustration for users.
  2. Blocked URLs: Some online platforms and security measures restrict the acceptance of shortened URLs due to their association with spam and phishing attempts. Consequently, certain URL shorteners have found themselves on spam blacklists, limiting their usability.
  3. Phishing Vulnerability: The inherent obscurity of shortened URLs, often represented by random characters, can be exploited by cybercriminals for phishing attacks. Scammers use these deceptive links to redirect users to seemingly legitimate websites designed to collect sensitive information, posing a significant security risk.

How to Build a URL Shortener in React with Shrtcode

The URL shortener we will create will include an input field for the original, long URL as well as a part for seeing the shortened URL. It will also contain the ability to copy the shortened URL to the clipboard, which will be accomplished through the use of react-copy-to-clipboard. Let’s get this party started:

Set up React (

Step-1 : Spin up a and set React sandbox on CoderPad:

How to Build a URL Shortener

Step-2 :Replace the information in App.tsx in the newly formed sandbox.

import { useState } from 'react';
import './App.css';

function App() {
  const [url, setUrl] = useState()
  const [shortendUrl, setShortenedUrl] = useState('')

  return (
    <div className="app">
      <div className='shortener'>
        <h2>URL shortener</h2>
        {/* form to enter URL to be shortened */}
        <form>
          <input
            placeholder='Enter URL'
            value={url}
            onChange={(e) => setUrl(e.target.value)}/>
          <button>Submit</button>
        </form>
        {/* Section to view shortened URLS */}
        {shortendUrl &&
          <div className='shortener__viewShot'>
            {shortendUrl}
          </div>
        }
      </div>
    </div>
  );
}

export default App;

We created a url to manage the input field and a shortendUrl state to store the abbreviated URL in the code block above.

Step-3 Next, modify App.css:

* {
  box-sizing: border-box;
}
.shortener {
  width: fit-content;
  margin: 0 auto;
  text-align: center;
}
.shortener input, button {
  height: 30px;
  padding: 0 10px;
}
.shortener input {
  border: 1px solid gray;
  color: rgb(64, 64, 66);
}
.shortener input:focus {
  border: 1px solid rgb(95, 180, 245);
  outline: none;
}
.shortener form > button {
  background-color: rgb(95, 180, 245);
  border: none;
  color: white;
}
.shortener form > button:hover {
  background-color: rgb(51, 162, 246);
}
.shortener__viewShot {
  margin-top: 20px;
  border: 1px solid gainsboro;
  display: flex;
  justify-content: space-between;
  padding-left: 10px;
  color: rgb(64, 64, 66);
  align-items: center;
}
.shortener__viewShot button {
  background-color: transparent;
  border: none;
  color: gray;
}
.shortener__viewShot button:hover {
  color: rgb(64, 64, 66);
}

The preview panel displays the modifications made by the sandbox and the URL shortener application:

How to shorten URLs with Shrtcode

“In order to create shortened URLs using Shrtcode, simply provide the URL as a query parameter to the designated API endpoint as detailed in their documentation. Proceed to the ‘App.tsx’ file and incorporate the following function following the ‘shortenedUrl’ state within the ‘App’ component:”

const shortenUrl = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch(
        `https://api.shrtco.de/v2/shorten?url=${url}`
      )
      const data = await response.json()
      setShortenedUrl(data.result.full_short_link);
    } catch (e) {
      alert(e);
    }
};

In the function mentioned earlier, we appended the original URL as a query parameter to Shrtcode’s shortening endpoint and initiated a GET request to that endpoint. Upon receiving the response, it is stored in the ‘shortenedUrl’ state variable.

Moving forward, to invoke this function when the Submit button is clicked, please make the following modification to the opening form tag within the App component:

<form onSubmit={shortenUrl}>
How to Build a URL Shortener

Copy shortened URL to the clipboard

Next, we’ll implement the functionality to copy the shortened URL to the clipboard when the copy button is clicked. To achieve this, we’ll incorporate the ‘react-copy-to-clipboard’ library. In the sandbox’s shell console, install this library by running the following command:

npm i react-copy-to-clipboard

Next, our next step involves passing the button responsible for triggering the copy function as a child component to the CopyToClipboard component. Additionally, we need to transmit the short URL to be copied as properties (props).

To accomplish this, we must begin by importing the CopyToClipboard component from the ‘react-copy-to-clipboard’ library. Following that, we should make the following modifications to the div element with the class name ‘shortener__viewShot’:

import {CopyToClipboard} from 'react-copy-to-clipboard';



<div className="shortener__viewShot">
  {shortendUrl}
  <CopyToClipboard text={shortendUrl}>
    <button onClick={() => alert("The URL has been copied")}>copy</button>
  </CopyToClipboard>
</div>

Once the copy button is activated within our application, the shortened URL will be swiftly copied to the clipboard, prompting the app to generate and display an alert confirming this action.

Complete App.tsx Code

import { useState } from 'react';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import './App.css';

function App() {
  const [url, setUrl] = useState()
  const [shortendUrl, setShortenedUrl] = useState('')

  const shortenUrl = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch(
        `https://api.shrtco.de/v2/shorten?url=${url}`
      )
      const data = await response.json()
      setShortenedUrl(data.result.full_short_link);
    } catch (e) {
      alert(e);
    }
  };

  return (
    <div className="app">
      <div className='shortener'>
        <h2>URL shortener</h2>
        {/* form to enter URL to be shortened */}
        <form onSubmit={shortenUrl}>
          <input
            placeholder='Enter URL'
            value={url}
            onChange={(e) => setUrl(e.target.value)}/>
          <button>Submit</button>
        </form>
        {/* Section to view shortened URLS */}
        {shortendUrl &&
          <div className="shortener__viewShot">
          {shortendUrl}
          <CopyToClipboard text={shortendUrl}>
            <button onClick={() => alert("The URL has been copied")}>copy</button>
          </CopyToClipboard>
        </div>
        }
      </div>
    </div>
  );
}

export default App;

You’re welcome! I’m glad you found the blog on “How to Build a URL Shortener” helpful. If you have any more questions or need further assistance, please don’t hesitate to reach out. Happy URL shortening, and best of luck with your projects!

Other Articles :

How to Install Node.js andNPM on Windows

Javascript course in 30 days — Day 1

Dairy Farm Shop Management System Using PHP and MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *