How to implement zendesk web widget to specific page on gatsby

Viewed 2873

Adding zendesk install script to the html.js file is working as expected and the widget is showing on all pages.

I want to show it on specific page like about-us page. I have tried this

render() {
return (
<>
<script
    id="ze-snippet"
    src="https://static.zdassets.com/ekr/snippet.js?key=xxx-xxxxx"
>
</script>
...
</>

But it doesn't work. Any idea?

2 Answers

In index.html file

<html>
    <body>
        <!-- your scripts -->

        <script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key={YOUR_KEY}"> </script>
        <!-- Hide de widget by default -->
        <script>zE('webWidget', 'hide')</script>
    </body>
</html>

In your component(s) to show

import React from 'react'

class MyComponent extends React.Component {

    constructor (props) {
        super(props)
    }

    componentDidMount () {
        // show widget on mount component
        zE('webWidget', 'show')
    }

    componentDidUnmount () {
        // hide widget on unmount component
        zE('webWidget', 'hide')
    }

    render () {
        // your render
        return (
            <div>Hello World</div>
        )
    }
}

In other components nothing need to do

To add <scripts> in your page with React (and so, with Gatsby) you have several options. The easiest to implement is using the <Helmet> component. You can check for further information in their docs. Basically, it handles your <head> tag:

This reusable React component will manage all of your changes to the document head.

Helmet takes plain HTML tags and outputs plain HTML tags. It's dead simple and React beginner-friendly.

To show this script only in /about-us page, you need to insert this snippet in your desired page:

import React from "react"
import Helmet from "react-helmet"
import Layout from "../components/layout"
import SEO from "../components/seo"

const AboutUs= () => (
 <>
   <>
      <Helmet>
        <script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=xxx-xxxxx">
      </Helmet>
   </>
    <Layout>
      <SEO title="About us" />
     <h1>I'm the about page</h1>
    </Layout>
 </>  
 )

export default AboutUs

It doesn't matter if you have a stateful or a stateless component, the idea is to wrap between <Helmet> component anything that you want to be placed in your <head>, in this case, a <script>.

Related