Reputation: 391
I am trying to load a gltf file in nextjs react using npm 'react-3d-viewer'.The gltf file is coming from database.
import {GLTFModel,AmbientLight,DirectionLight} from 'react-3d-viewer'
import React, { Suspense } from "react";
import getConfig from "next/config";
import axios from "axios";
const config = getConfig();
class ModalDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
apiUrl: config.publicRuntimeConfig.publicRuntimeConfigValue.apiUrl,
filePath: '',
};
}
render() {
return (
<div className="App">
<div>
<p>okay</p>
<GLTFModel
src={this.state.apiUrl + '/api/v1/visitImageRequirementInfo/getImageByImagePathId?imagePath=' + this.state.filePath}>
<AmbientLight color={0xffffff}/>
<DirectionLight color={0xffffff} position={{x:100,y:200,z:100}}/>
<DirectionLight color={0xff00ff} position={{x:-100,y:200,z:-100}}/>
</GLTFModel>
</div>
</div>
);
}
}
export default ModalDemo;
The filePath attribute contains the value of gltf which has the value like this
visitImageDirectory/4f2f0f63-e57b-4eb8-b3d5-c4a2413cd2bd.gltf
and its coming by get request in the componetDidMount function from database .All i am getting this error:
ReferenceError: window is not defined
This is my next.config.js file if it has anything to do with it
const withCSS = require('@zeit/next-css');
const withImages = require('next-images');
const withPlugins = require('next-compose-plugins');
module.exports = withPlugins([
[withCSS, { cssModules: true }],
[withImages],
], {
serverRuntimeConfig: { serverRuntimeConfigValue: 'test server' },
// publicRuntimeConfig: { publicRuntimeConfigValue: {apiUrl:'http://127.0.0.1:5000'} },
publicRuntimeConfig: { publicRuntimeConfigValue: {apiUrl:process.env.apiUrl.trim()} },
webpack: (config, options) => { return config; } ,exportTrailingSlash: true
});
How can i resolve this issue. or any other library i can use to show the gltf file is nextjs from database?
Upvotes: 1
Views: 1114
Reputation: 2571
You get this error because the library is accessing window property on server, as Next.js Renders components Server side. So the best thing you can do here (if you don't mind server side benefits for this particular component) is using dynamic imports with ssr: false
.
import dynamic from 'next/dynamic';
const AmbientLight = dynamic(() =>
import('react-3d-viewer').then((mod) => mod.AmbientLight),{ssr: false}
)
const GLTFModel = dynamic(() =>
import('react-3d-viewer').then((mod) => mod.GLTFModel),{ssr: false}
)
const DirectionLight = dynamic(() =>
import('react-3d-viewer').then((mod) => mod.DirectionLight),{ssr: false}
)
Upvotes: 3