the Easiest way to add React Meta Tags / OG for SEO and Social Media

Using different libraries can solve this problem of meta tags, but also adding more problems of maintainance and following the library contributors, however React is a direct solution for this problem without depending on different packages. 

 

How? 

simple answer is to use the JS useEffect hook, which will trigger once for every page and can run simillar to component will mount which been deprecated within the new react version, instead used component did mount hook. 

 

Solution? 

Simple solution that we can use is to apply the new appendChild into the head and add the meta that we needs to support our page on load once and for each by choice. 

from

ReactJS out of the box Meta Tags

to

Meta Tags solution

 

Depth Explanaition

In this component we are requesting from the props to include for us the page tags by choice, prefered to have a value but in general it's an optional use for developers to assign tags or not from different components

Component Code

 

Starting with the minimum Global Tags or OG, these are the social media requirements to include your site in a good card to share, else your link will not include any and you will see only the domain single line with no image or description under it.

Second basic meta tags which we kept for Search engines optimization like type, title, desription, keywords and so on. 

In this solution we will cover all of them with simple useEffect() or componentdidmount() within react, easy and with no extra libraries to use out of the box

/**

* By Sam Ayoub [email protected]

* Copyright: IST

* This component to auto build meta tags for reactJS

*/

import React, { useEffect } from "react";

export default function MetaTags (props) {

const metaTags = [

{name: "title", content: props.title},

{name: "description", content: props.description.substring(0, 75) },

{name: "keywords", content: props.keywords},

{name: "author", content: props.author},

{name: "og:locale", content: "en_US"},

{name: "og:title", content: props.title},

{name: "og:image", content: props.image},

{name: "og:url", content: window.location.href},

{name: "og:type", content: props.type},

{name: "og:sitename", content: props.sitename},

{name: "og:description", content: props.description.substring(0, 75)},

{name: "twitter:title", content: props.title},

{name: "twitter:image", content: props.image},

{name: "twitter:url", content: window.location.href},

{name: "twitter:card", content: props.description.substring(0, 75)}

]

// Inject Meta Tags

useEffect(() => {

// Add title first as #1

document.head.innerHTML+=`

 

${props.sitename} | ${props.title}

`;

// Now we sync out meta tags

metaTags.map(m => {

var meta = document.createElement('meta');

meta.name = m.name;

meta.content = m.content;

document.head.appendChild(meta);

})

 

}, [])

return;

}

 

In general the code above is only needed to run once in any other UI component, so to make sure we run it the right way, we should make sure that we covered the required minimum tags as below

  1. title={"Homepage"} // Your title which will be converted into browser friendly title as sitename | title

  2. sitename={"Video Downloader"} // Your main site name

  3. description={"Video Downloader, free downloader for all videos around the internet, youtube, vimeo, tiktok and more"} // Description, doesn't matter how long, as in our code above we already limited to 75 so feel free to add as much as you like

  4. image={window.location.protocol + "//" + window.location.host + "/logo512.png"} // Prefered to be dynamic not static, simply as the location host and protocol 

  5. keywords={"Video, Downloader, ads, blocker, free, download, videos, internet, youtube, vimeo, tiktok, no ads"} // Keywords by choice

  6. type="tool" // What your site is all about, specificly this page, like the list of types below

  7. author="DDKits.com" // Your site Author can be a name for articles or domain as you see in this example

og:Type Lists Of Objects

apps.saves An action representing someone saving an app to try later.

article This object represents an article on a website. It is the preferred type for blog posts and news stories.

book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines

books.author This object type represents a single author of a book.

books.book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books

books.genre This object type represents the genre of a book or publication.

books.quotes Returns no data as of April 4, 2018.

An action representing someone quoting from a book.

books.rates Returns no data as of April 4, 2018.

An action representing someone rating a book.

books.reads Returns no data as of April 4, 2018.

An action representing someone reading a book.

books.wants_to_read Returns no data as of April 4, 2018.

An action representing someone wanting to read a book.

business.business This object type represents a place of business that has a location, operating hours and contact information.

fitness.bikes Returns no data as of April 4, 2018.

An action representing someone cycling a course.

fitness.course This object type represents the user's activity contributing to a particular run, walk, or bike course.

fitness.runs Returns no data as of April 4, 2018.

An action representing someone running a course.

fitness.walks Returns no data as of April 4, 2018.

An action representing someone walking a course.

game.achievement This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has a game:points value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.

games.achieves An action representing someone reaching a game achievement.

games.celebrate An action representing someone celebrating a victory in a game.

games.plays An action representing someone playing a game. Stories for this action will only appear in the activity log.

games.saves An action representing someone saving a game.

music.album This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.

music.listens Returns no data as of April 4, 2018.

An action representing someone listening to a song, album, radio station, playlist or musician

music.playlist This object type represents a music playlist, an ordered collection of songs from a collection of artists.

music.playlists Returns no data as of April 4, 2018.

An action representing someone creating a playlist.

music.radio_station This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.

music.song This object type represents a single song.

news.publishes An action representing someone publishing a news article.

news.reads Returns no data as of April 4, 2018.

An action representing someone reading a news article.

og.follows An action representing someone following a Facebook user

og.likes An action representing someone liking any object.

pages.saves An action representing someone saving a place.

place This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.

product This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.

product.group This object type represents a group of product items.

product.item This object type represents a product item.

profile This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. The fb:profile_id field associates the object with a Facebook user.

restaurant.menu This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.

restaurant.menu_item This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.

restaurant.menu_section This object type represents a section in a restaurant's menu. A section contains multiple menu items.

restaurant.restaurant This object type represents a restaurant at a specific location.

restaurant.visited An action representing someone visiting a restaurant.

restaurant.wants_to_visit An action representing someone wanting to visit a restaurant

sellers.rates An action representing a commerce seller has been given a rating.

video.episode This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.

video.movie This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.

video.other This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use the video.movie or video.tv_show object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)

video.rates Returns no data as of April 4, 2018.

An action representing someone rating a movie, TV show, episode or another piece of video content.

video.tv_show This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use the video.episode object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)

video.wants_to_watch Returns no data as of April 4, 2018.

An action representing someone wanting to watch video content.

video.watches Returns no data as of April 4, 2018.

An action representing someone watching video content.

To use this component we created or function as the example above, we just need to call it within our react if static metatags then just use app.js as main place and it will repeat for all other pages with same results

 

import MetaTags from './MetaTags.js'

...

 

title={"Homepage"}

sitename={"Video Downloader"}

description={"Video Downloader, free downloader for all videos around the internet, youtube, vimeo, tiktok and more"}

image={window.location.protocol + "//" + window.location.host + "/logo512.png"}

keywords={"Video, Downloader, ads, blocker, free, download, videos, internet, youtube, vimeo, tiktok, no ads"}

type="media"

author="DDKits.com"

/>

 

We still can improve our code by running with routes and window location dependancies for dynamic changes or routes in recursive pages

// Inject Meta Tags

useEffect(() => {

// Now we sync out meta tags

metaTags.map(m => {

var meta = document.createElement('meta');

meta.name = m.name;

meta.content = m.content;

// Remove old tag and add new one

document.querySelector(`meta[name='${m.name}']`)?.remove()

document.head.appendChild(meta);

})

// Add title first as #1

if (document.querySelector(`title`)) {

document.querySelector(`title`).innerHTML = (`${props.sitename} | ${props.title}`).toString();

}else{

document.head.innerHTML+=`

${props.sitename} | ${props.title}

`;

}

 

}, [window.location.href])

The improvment is to update and remove similar tags if exist, simly to make sure we are not duplicating tags around

 

That's all no need for helmet or other libraries to do this simple process, this will make the site cover from a SEO and OG prespective the rest on you

 

Regards 

Sam Ayoub 

https://ddkits.com

By: Mutasem Elayyoub