"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to embed link with preview in React Application

How to embed link with preview in React Application

Published on 2024-11-08
Browse:825

Introduction

When building a web application, it's often useful to show a preview of a link's content—like how social media platforms show link previews when you share a URL. So instead of just url text you can show og informations like pictures and desccription as well, beside url.

In this post, I'll walk you through embedding links in a React app, while fetching Open Graph metadata (such as title, image, and description) using axios and cheerio for scraping the target page's HTML.

We’ll create a simple EmbeddedLink component that fetches and displays Open Graph metadata for any provided URL.

Prerequisites

Before we start, make sure you have the following installed:

  1. React – Set up a React project using Create React App or any method you prefer.
  2. Axios – For making HTTP requests.
  3. Cheerio – For parsing and scraping HTML (a server-side jQuery-like library usually used for scraping).

You can install Axios and Cheerio using the following commands:

npm install axios cheerio

Step 1: Creating the EmbeddedLink Component

We'll create a new EmbeddedLink component that takes in a url as a prop and fetches the Open Graph metadata from that link which we will use later on. Here's the full code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import cheerio from 'cheerio';

const EmbeddedLink = ({ url }) => {
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [imageUrl, setImageUrl] = useState('');
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');

    useEffect(() => {
        const fetchOGData = async () => {
            try {
                const response = await axios.get(url, {
                    headers: {
                        'origin': 'https://mysite.com'
                    }
                });
                const html = response.data;

                // Parse HTML content using Cheerio
                const $ = cheerio.load(html);
                const ogImage = $('meta[property="og:image"]').attr('content');
                const ogTitle = $('meta[property="og:title"]').attr('content');
                const ogDesc = $('meta[property="og:description"]').attr('content');

                setImageUrl(ogImage || '');
                setTitle(ogTitle || '');
                setDescription(ogDesc || '');
                setLoading(false);
            } catch (error) {
                setError(error);
                setLoading(false);
            }
        };

        fetchOGData();
    }, [url]);

    if (loading) return 
Loading...
; if (error) return
Error: {error.message}
; return (
{imageUrl && {title}} {title &&

{title}

}
{!imageUrl && !title &&

No preview available

}

{description}

{url}

); }; export default EmbeddedLink;

Step 2: Using the EmbeddedLink Component

You can now use the EmbeddedLink component in your React app like this:

import React from 'react';
import EmbeddedLink from './EmbeddedLink';

function App() {
    return (
        

Link Preview Example

); } export default App;

This will render a preview of the URL provided, with its image, title, and description.

Handling Errors and Loading States

We handle potential errors and loading states by showing appropriate messages to the user:

  • While the metadata is being fetched, a simple "Loading..." message is shown or you can use some animation spinner or whatever.
  • If something goes wrong during the fetch (e.g., a network issue), the error message is displayed.

Conclusion

When you are done, you should be able to see result like on the picture below.

How to embed link with preview in React Application

I prefer this dev.to embedded link style, but you can style it whatever you like and prefer.

Release Statement This article is reproduced at: https://dev.to/basskibo/how-to-embed-link-with-preview-in-react-application-2gdd?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3