-
-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create OpenGraphPreview component to fetch and parse metadata. Integrate into LinkPreview to show if no other preview available. Implement polished styling for clean, readable design.
- Loading branch information
Showing
3 changed files
with
83 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { useEffect, useState } from 'react'; | ||
|
||
export default function OpenGraphPreview({ url }) { | ||
const [data, setData] = useState(null); | ||
|
||
useEffect(() => { | ||
async function fetchData() { | ||
const response = await fetch(url); | ||
const html = await response.text(); | ||
const doc = new DOMParser().parseFromString(html, 'text/html'); | ||
|
||
const metaContent = (property) => | ||
doc.querySelector(`meta[property="${property}"]`)?.getAttribute('content'); | ||
|
||
const [title, description, image, source] = [ | ||
'og:title', | ||
'og:description', | ||
'og:image', | ||
'og:site_name', | ||
].map(metaContent); | ||
setData({ title, description, image, source }); | ||
} | ||
fetchData(); | ||
}, [url]); | ||
if (!data || data.title === undefined) { | ||
return null; | ||
} | ||
|
||
return ( | ||
<div className="opengraph-preview"> | ||
{data.image && <img className="opengraph-image" src={data.image} alt={data.title} />} | ||
<div> | ||
<div className="opengraph-title">{data.title}</div> | ||
<div className="opengraph-description">{data.description}</div> | ||
<div className="opengraph-source">{data.source}</div> | ||
</div> | ||
</div> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters