Skip to content

Instantly share code, notes, and snippets.

@foloinfo
Last active December 15, 2020 01:33
Show Gist options
  • Save foloinfo/d4c75e44f2d28a341577d162a33271fb to your computer and use it in GitHub Desktop.
Save foloinfo/d4c75e44f2d28a341577d162a33271fb to your computer and use it in GitHub Desktop.
react meta tags with react-navigation
import { useCallback } from 'react'
import { useFocusEffect } from '@react-navigation/native'
import { Platform } from 'react-native'
const setTags = (tags)=> {
if(Platform.OS !== 'web') return
Object.keys(tags).forEach(key => {
const meta = document.createElement('meta')
meta.name = key
meta.content = tags[key]
document.getElementsByTagName('head')[0].appendChild(meta)
})
}
const clearTags = (tags)=> {
if(Platform.OS !== 'web') return
Object.keys(tags).forEach(key => {
const meta = document.getElementsByName(key)[0]
meta.parentNode.removeChild(meta)
})
}
const useClearErrors = (tags)=> {
useFocusEffect(
useCallback(() => {
// Do something when the screen is focused
meta.setTags(tags)
return () => {
// Do something when the screen is unfocused
meta.clearTags(tags)
}
}, [])
)
}
export default useClearErrors
...
import useMetaTags from 'hooks/useMetaTags'
const UseMetaTagScreen = props => {
// it will set / unset meta tags on screen enter / leave
useMetaTags({ robots: 'noindex' })
...
}
@foloinfo
Copy link
Author

I didn't know https://github.com/lordgiotto/react-metatags-hook exist until I wrote my simple code.
I leave it here anyway if someone wants to know how to use this kind with the react-navigation env.
I'm using it on expo web.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment