0

I am getting **Unexpected token '&'** error while declaring globle variable .I also tried to stringily it's value but still getting same error why ?

I am doing like this.

<Head>
 

   {
      <script type="text/javascript">
        var s_pageName2=JSON.stringify('abc:en-us:/lo-form')
      </script>
    }
  </Head> 

here is my whole code https://codesandbox.io/s/long-bird-tgwcv?file=/pages/index.js

Ia m using nextjs framework . I want to create global variable having value this abc:en-us:/lo-form

This is not codesandbox error .I am facing same issue on my local machine

enter image description here

user944513
  • 12,247
  • 49
  • 168
  • 318

1 Answers1

0

In jsx you cannot just do that, you can use dangerouslySetInnerHTML, but i highly discourage to use it.

<script
  dangerouslySetInnerHTML={{
    __html: ` var s_pageName2='abc:en-us:/lo-form'`
  }}
/>

If you want to store a global variable to reuse in any of your components there are differents ways for achieve that, for example using react Context and expose a custom hook to use wherever you need to.

Example :

_app.js

    import { MyProvider} from '../components/MyProvider'
    
    
    function MyApp({ Component, pageProps }) {
        return (
                <MyProvider>
                    <Component {...pageProps} />
                </MyProvider>
        )
    }

export default MyApp

/components/MyProvider :

import React, { useState, useEffect,useContext } from 'react'
export const MyContext= React.createContext(null)

export function MyProvider ({ children }) { 
    const [myVar, setMyVar] = useState('abc:en-us:/lo-form')
    return (
        <MyContext.Provider value={{myVar}}>
            {children}
        </MyContext.Provider>
        
        )
 }

export function useApp() {
    const value = useContext(MyContext)
    return value
}

Then in any other component / page you can just use your hook in this way :

import { useApp } from './components/MyProvider'
const MyPage= () => {
  const {myVar} = useApp()
   ... rest of code

}

This is just an example, you can achieve that in many ways, it depends on your app business logic.

Nico
  • 6,259
  • 4
  • 24
  • 40
  • thanks Nico..I was using first method. variable is set . but it give new error `Uncaught SyntaxError: Unexpected end of input` – user944513 Sep 02 '21 at 14:54
  • actually I want to set a variable on window so that other script 3 party script can read that value do the stuff – user944513 Sep 02 '21 at 14:55
  • https://codesandbox.io/s/hungry-breeze-frosm this works for me. – Nico Sep 02 '21 at 14:58