NextJS - window is not defined

17,959

What you need to do is dynamic import with No SSR

Try this:

import React, { Component } from 'react';
import dynamic from 'next/dynamic';

const Typewriter = dynamic(
    () => import('typewriter-effect'),
    {
        ssr: false
    }
)

class Home extends Component {
    render() {
        return (
            <Typewriter
                onInit={(typewriter) => {
                    typewriter.typeString('Hello World!')
                        .callFunction(() => {
                            console.log('String typed out');
                    })
                        .pauseFor(2500)
                        .deleteAll()
                        .callFunction(() => {
                            console.log('All strings were deleted');
                    })
                        .start();
            }}
            />
        )
    }
}

export default Home;
Share:
17,959

Related videos on Youtube

Student22
Author by

Student22

Updated on September 15, 2022

Comments

  • Student22
    Student22 over 1 year

    I'm trying to import Typewriter Effect into my NextJS project, but whenever I do, I get this error that reads the following:

    ReferenceError: window is not defined

    and from what I've read, the error is displaying because it's trying to load the library on the server-side rather than the client-side.

    So when I simply try to import it like this:

    import Typewriter from 'typewriter-effect'

    the error promptly displays.

    People suggested that I try something like this:

    let Typewriter
    if (typeof window !== 'undefined') {
      Typewriter = require( 'typewriter-effect' )
    }
    

    however, it doesn't work like this either. I get an error that reads the following:

    Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

    I've searched a lot of places for a potential solution to this problem, but I've been unsuccessful with my attempts.

  • Kirill
    Kirill about 4 years
  • Karin C
    Karin C about 4 years
    Thanks @Kirill! not sure when they changed it, but I updated the link in my response