Window is not defined with NextJS when using Elastic UI

686 views Asked by At

Just trying to add a button from the Elastic UI library but just getting a window is not defined when adding in the button. The API call and everything else works fine until I add the button component or as soon as I add in the import on line 3 below.

Is there a way to use the Elastic UI library when making a server side api call?

Here is the main code:

import React from "react";
import "isomorphic-unfetch";
import { EuiButton } from "@elastic/eui";

export default class HomePage extends React.Component {
  static async getInitialProps() {
    let res = await fetch("https://api.randomuser.me/");
    let randUser = await res.json();
    console.log(randUser);
    return { users: randUser };
  }

  render() {
    return (
      <div>
        <h2>User info:</h2>
        <ul>
          {this.props.users.results.map((user, i) => {
            return <li key={"user-" + i}>{user.gender}</li>;
          })}
        </ul>
        <EuiButton href="http://www.elastic.co">Link to elastic.co</EuiButton>
      </div>
    );
  }
}
1

There are 1 answers

0
Pierfrancesco On

Don't know if this could be the correct solution, but I'd explore next dynamic import.

I managed to get the previous code works from my side, but don't know if then the render button is 100% the one that you're expecting.

import React from "react";
import dynamic from 'next/dynamic'
import "isomorphic-unfetch";

export default class HomePage extends React.Component {
  static async getInitialProps() {
    let res = await fetch("https://api.randomuser.me/");
    let randUser = await res.json();
    console.log(randUser);
    return { users: randUser };
  }

  render() {
    // dynamic import of the button
    const EuiButton = dynamic(() => import('@elastic/eui/').then(module => module.EuiButton))

    return (
      <div>
        <h2>User info:</h2>
        <ul>
          {this.props.users.results.map((user, i) => {
            return <li key={"user-" + i}>{user.gender}</li>;
          })}
        </ul>
        {/*render it only if we're from client side*/}
        {process.browser ? <EuiButton href="http://www.elastic.co">Link to elastic.co</EuiButton> : null }
      </div>
    );
  }
}

Hope this could give you an idea how to tackle your issue.