Make a Long URL Short and Share it from React Native App

URL Shortener in React Native

This post contains How to Make a Long URL Short and Share it from React Native App. We will see what is a URL shortener, how it works, and how it can help you. So let’s get started.

If you guys have observed the text messages closely then you have seen that nobody sends the original URL of their product or service in the message nowadays instead they send a short URL from bit.ly or any other URL shortener. URL shorteners are very famous nowadays. It helps you to shorten your URL, you just have to provide the long URL to the API and in return, it provides you with a new short URL to share. This way you can save your text character and your audience can see the message clearly instead of long redundant URLs.

There are many URL Shortener sites on the internet to do this job for free and TinyURL is one of them that we are going to use in this example. These URL shorteners can help you lot in many ways:

  1. It provides a sweet and beautiful small URL.
  2. It reduces the character used for the URL in the text message.
  3. Some sites also provide analytics about the click on the link and the user behavior as whenever the user clicks the URL they reach your site using these short URLs.
  4. You can properly convey your message to the audience instead of a big lengthy URL.

Other than that you can also find ways how can you make it useful to you.

How to Shorten the URL?

To Shorten a URL you just have to find a URL Shortner API and have to pass the URL with the parameter they want. I have used TinyURL for this example and here is how I have to pass my long URL

https://tinyurl.com/api-create.php?url=https://aboutreact.com/questions-and-answers-for-interview-preparation/

In response to that, it provides me the short URL as text

https://tinyurl.com/y2u6p7al

Look how simple it was. now let’s move towards the code and see how to call an HTTP call to get the short URL and use a Share API provided by React Native to share that URL with Message.

In this example, we are going to make a screen with 1 button and on the click of the button, we will call the URL shortener to provide a short URL, after getting the short URL we will add a short message with the response URL and will call a Share API to share the message on all the possible channels available.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Code to Make a Long URL Short and Share

Now Open App.js in any code editor and replace the code with the following code

App.js

// Make a Long URL Short and Share from React Native App
// https://aboutreact.com/long-url-short-and-share/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Share,
} from 'react-native';

const App = () => {
  const getDataUsingGet = () => {
    //GET request to convert our long URL to short one
    fetch(
      'https://tinyurl.com/api-create.php?url=https://aboutreact.com/questions-and-answers-for-interview-preparation/',
      {
        method: 'GET',
      },
    )
      .then((response) => response.text())
      //Response to text
      .then((responseJson) => {
        //Printing the Response String
        console.log(responseJson);
        //responseJson is our short URL
        //Sharing the short URL with our message
        Share.share({
          message:
            'Hey, I found very important interview questions of React Native. You can also read it by clicking on the link ' +
            responseJson,
        })
          .then((result) => console.log(result))
          .catch((errorMsg) => console.log(errorMsg));
      })
      //If response is not in text then in error
      .catch((error) => {
        //Error
        alert('Error -> ' + JSON.stringify(error));
        console.error(error);
      });
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.titleText}>
          Example of URL Shorter using www.tinyurl.com
        </Text>
        <Text style={styles.textStyle}>Long URL</Text>
        <Text style={styles.textStyleSmall}>
          URL: https://aboutreact.com/questions-and-answers-for-interview-preparation
        </Text>
        <Text style={styles.textStyle}>
          After Shortening the URL
        </Text>
        <Text style={styles.textStyleSmall}>
          https://tinyurl.com/y2u6p7al
        </Text>
        <TouchableOpacity
          activeOpacity={0.7}
          style={styles.buttonStyle}
          onPress={getDataUsingGet}>
          <Text style={styles.buttonTextStyle}>
            Share Messgae with Short URL
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    justifyContent: 'center',
    textAlign: 'center',
  },
  titleText: {
    padding: 8,
    fontSize: 22,
    textAlign: 'center',
    fontWeight: 'bold',
  },
  textStyle: {
    textAlign: 'center',
    fontSize: 18,
    color: '#000',
    marginTop: 15,
  },
  textStyleSmall: {
    textAlign: 'center',
    padding: 5,
  },
  buttonStyle: {
    justifyContent: 'center',
    flexDirection: 'row',
    marginTop: 30,
    padding: 15,
    backgroundColor: '#8ad24e',
  },
  buttonTextStyle: {
    color: '#fff',
    textAlign: 'center',
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device:

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

      

This is how to make a long URL short and share it from React Native App. If you have any doubts or want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

2 thoughts on “Make a Long URL Short and Share it from React Native App”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.