Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS - window is not defined

Tags:

next.js

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.

like image 323
Student22 Avatar asked May 27 '19 05:05

Student22


1 Answers

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;
like image 73
Karin C Avatar answered Oct 20 '22 23:10

Karin C