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.
Before we start, make sure you have the following installed:
You can install Axios and Cheerio using the following commands:
npm install axios cheerio
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) returnLoading...; if (error) returnError: {error.message}; return ( ); }; export default EmbeddedLink;
You can now use the EmbeddedLink component in your React app like this:
import React from 'react'; import EmbeddedLink from './EmbeddedLink'; function App() { return (); } export default App;Link Preview Example
This will render a preview of the URL provided, with its image, title, and description.
We handle potential errors and loading states by showing appropriate messages to the user:
When you are done, you should be able to see result like on the picture below.
I prefer this dev.to embedded link style, but you can style it whatever you like and prefer.
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