How To Shorten A Url In Your React App? Most easiest way.!!

Karan Rajput
3 min readDec 13, 2020

Are you also tired of the long URLs? Let’s shorten a Url easily in your React App. We will use bit.ly API but with the help of a NPM package “bitly-react”. So lets get started..!!

First create your react app with any name you want. Now open terminal and start your react app with :-

npm start

Now open another terminal and install bitly-react by running the following command :-

npm i bitly-react

Now the setup is completed..!!

Now create a new file with any name you want, i am making “ShortUrl.jsx”. This will be the component which will return us the shorten Url.

Open the file and write the template code for React component.

ShortUrl.jsx

Now import the “BitlyClient” from bitly-react package.

ShortUrl.jsx

Now create a new instance of the BitlyClient and store it in a constant variable. Here you’ll need an access token of bitly API. You can generate one here. Put that access token in the place of : “Your_access_token

ShortUrl.jsx

Make an empty state with the help of useState to store shortened url.

ShortUrl.jsx

Now let’s create a function which takes long Url as parameter and set the shortened url to the shortenUrl state.

ShortUrl.jsx

We are using try/catch to handle error. If shortening the url fails because of any reason, it will show the error in console.

The if condition will check if the shortened url is not empty or null. If not, then it will set the state of shortenUrl the returned shortened url.

Now, call the function and pass a long url as parameter.

ShortUrl.jsx

So now we have shortened url stored in shortenUrl. Let’s show it in a h1 tag.

ShortUrl.jsx

Now, open App.js and import the ShortUrl component. Use the ShortUrl component.

Now run the code with the help of

npm start

It will open http://localhost:3000/ in your default browser. And boom..!! you’re done.!

Open that shortened url and it will redirect you to the long url you gave as parameter to the getShortUrl function.

Thanks for reading, I hope u like it..!!

--

--