Search code examples
javascriptreactjsgatsby

How to add eternal script tag in Gatsby body ? With conditional rendering of script in body Tag?


For Example : -

  const country = "USA" 
    import chat = ('./utils/script'); // script can be imported  from a file
     if(country ="USA")   //  used in component conditionally  
{chat}
else
{ console.log("Not USA")}

tell me without using html.js or gatsby


Solution

  • You have many ways of achieving this:

    If you need some UI logic, you can do:

    const IndexPage = () => (
      <div>
        <Helmet>
          {country === "USA" && <script src={withPrefix('./utils/script')} type="text/javascript" />
         }
        </Helmet>
    
      </div>
    )
    export default IndexPage
    

    More details about withPrefix (it may not be needed) helper: https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-link/#add-the-path-prefix-to-paths-using-withprefix

    You can achieve the same result by using gatsby-ssr.js along with onRenderBody API with the exposed setPostBodyComponents function:

    export const onRenderBody = ({ setPostBodyComponents }) => {
      if(country ==="USA"){
        setPostBodyComponents([
            <script src='./utils/script' />,
        ])
      }
    }
    

    More details about gatsby-ssr.js and onRenderBody API: https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr/