简体   繁体   中英

Add script tag to React component without using props or context in NextJS

I want to add a library to my React component as a script tag. I'm doing this currently by calling an API in an _app.tsx file then accessing the value in a _document.tsx file. Within _document.tsx I add the script tag to the document head by passing it to a custom component.

My ultimate goal is to remove it from NEXT_DATA (I'm working on a SSR Next JS app).

Any ideas? I've looked into using window, but have not had success there.

Note: Updated question for clairty.

You can use the Next.js Head tag from anywhere in your app to achieve loading a script.

For example:

    import Head from 'next/head';
    
    function MyLibraryLoader() {
        return (
            <Head>
                <script src="..." type="text/javascript" />
            </Head>
        )
    }

More about the Head tag can be found here: https://nextjs.org/docs/api-reference/next/head

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM