Next.js: document is not defined

后端 未结 6 1697
一个人的身影
一个人的身影 2021-02-07 15:22

I am trying to create a payment form where people can pay but I keep getting this error.

document is not defined

I\'m using Next.js. Ple

6条回答
  •  死守一世寂寞
    2021-02-07 15:46

    You have to make sure you have two things setup.

    1. DOM render is completed.
    2. Then load the function.

    Step 1: create hook isMounted this will make sure that your DOM is rendered.

    import React, {useEffect, useState} from 'react';
    
    function RenderCompleted() {
    
        const [mounted, setMounted] = useState(false);
    
        useEffect(() => {
            setMounted(true)
    
            return () => {
                setMounted(false)
            }
        });
    
        return mounted;
    }
    
    export default RenderCompleted;
    

    Inside function Payment load the hook :

    import React, {useEffect} from "react";
    import {Elements, StripeProvider} from 'react-stripe-elements';
    import CheckoutForm from '../../components/Payment/CheckoutForm';
    import { useRouter } from 'next/router';
    import RenderCompleted from '../hooks/isMounted';
    
    var stripe_load = () => {
        var aScript = document.createElement('script');
        aScript.type = 'text/javascript';
        aScript.src = " https://js.stripe.com/v3/";
    
        document.head.appendChild(aScript);
        aScript.onload = () => {
    
        };
    };
    
    function Payment({host}) {
        const[key,setKey] = useEffect('');
    
        //will help you on re-render or host changes
    
        useEffect(()=>{
            const key = host.includes('localhost') ? 'test' : 't';
            setKey(key);
        },[host])
    
    
        useEffect(() => {
          var aScript = document.createElement('script');
           aScript.type = 'text/javascript';
           aScript.src = " https://js.stripe.com/v3/";
    
           document.head.appendChild(aScript);
           aScript.onload = () => {
    
           };
        }, [isMounted])
    
    
        const router = useRouter();
        const isMounted = RenderCompleted();
    
        return (
            


    Powered by Stripe

    ); }; Payment.getInitialProps = async ctx => { return { host: ctx.req.headers.host } }; export default Payment

    Another way to do this is, to use head component of next.js: https://nextjs.org/docs/api-reference/next/head

    
            My page title
            
          
    

提交回复
热议问题