react-d3-tree: ReferenceError: window is not defined - Server-Side Rendering (SSR)

How to use this great library properly with Server-Side Rendering (SSR)

ReferenceError: window is not defined

- react-d3-tree.min.js:1 
    [frontend]/[react-d3-tree]/lib/react-d3-tree.min.js:1:4937
  
  - react-d3-tree.min.js:1 
    [frontend]/[react-d3-tree]/lib/react-d3-tree.min.js:1:4899
  
  - react-d3-tree.min.js:1 e.exports
    [frontend]/[react-d3-tree]/lib/react-d3-tree.min.js:1:5409

return window&&document&&document.all&&!window.atob

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Comments: 15 (9 by maintainers)

Most upvoted comments

@thomashibbard same window not defined issue even with NoSSR. I finally got it working by doing a inline import

const Tree = require('react-d3-tree').Tree;
return (
  <div style={{width: '100vw', height: '100vh'}}>
    <Tree data={data} onClick={this.onClick} />
  </div>
);
let Tree = ' '
class MyComponent extends React.PureComponent {
   state = {
   	redender: false
   };
   async componentDidMount() {
   	let res = await import("react-d3-tree");
   	Tree = res.Tree;
   	this.setState({ redender: true, window });
   }
   render() {
   	return <div style={{ height: 1000, width: 1000 }}>{this.state.redender && <Tree data={myTreeData} />}</div>;
   }
}

this worked for me

@codemonkeycxy you can also use npm’s package react-no-ssr as a workaround

https://github.com/kadirahq/react-no-ssr/blob/master/src/index.js

Hi @bkrem Thank you for your almost instantaneous answer. Yes, I checked that too. I built it without UglifyJsPlugin and it’s used for

isOldIE = memoize(function() {
	// Test for IE <= 9 as proposed by Browserhacks
	// @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
	// Tests for existence of standard globals is to allow style-loader
	// to operate correctly into non-standard environments
	// @see https://github.com/webpack-contrib/style-loader/issues/177
	return window && document && document.all && !window.atob;
}),

I investigated problem a little https://github.com/webpack-contrib/style-loader/blob/67120f8dc831626f466d64513b4e26074e89341b/lib/addStyles.js#L23 Problem occures during import

// react-d3-tree.js
module.exports = function(list, options) {
  // Here DEBUG is not defined
  if (typeof DEBUG !== "undefined" && DEBUG) {
    if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
  }

  options = options || {};

  options.attrs = typeof options.attrs === "object" ? options.attrs : {};

        // Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
        // tags it will allow on a page
  if (!options.singleton) options.singleton = isOldIE();