NodeToy / react-nodetoy

https://react-nodetoy.vercel.app/
MIT License
61 stars 8 forks source link

Example of working code implementation with NextJS #3

Open foufrix opened 1 year ago

foufrix commented 1 year ago

Hi, I just tried to make the code snippet works with NextJS.

I have as error document not find from nodetick : error - ReferenceError: document is not defined at de (/Users/raf/Documents/project/node_modules/@nodetoy/react-nodetoy/dist/react-nodetoy.umd.js:1:1490)

I then implemented the shader as a standalone component and import it using next/dynamic with SSR off:

Shader.tsx

import { NodeToyMaterial, NodeToyTick } from '@nodetoy/react-nodetoy';
import { data } from 'utils/shaderData';

export default function Shader() {
  return (
    <>
      <mesh>
        <boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
        <NodeToyMaterial data={data} />
      </mesh>
      <NodeToyTick />
    </>
  );
}

App.tsx

import { OrbitControls } from '@react-three/drei';
import { Canvas } from '@react-three/fiber'
import dynamic from 'next/dynamic';

export const App = () => {
  const Shader = dynamic(() => import('./Shader'), { ssr: false });
  return (
    <div style={{ width: '100vw', height: '100vh' }}>
      <Canvas camera={{ fov: 75, near: 0.1, far: 1000, position: [0, 0, 2] }}>
        <ambientLight intensity={0.5} />
        <directionalLight position={[-10, -10, -5]} intensity={0.5} />
        <Shader />
        <OrbitControls />
      </Canvas>
    </div>
  );
};

This bypass the document error but trigger Error: R3F: Hooks can only be used within the Canvas component!.

Any idea on how to solve that? A nextjs implementation would be helpful, thanks 🙏

foufrix commented 1 year ago

adding if (typeof window === 'undefined') return <></>; before the return component trigger a new issue Error: Hydration failed because the initial UI does not match what was rendered on the server.

mokargas commented 1 year ago

adding if (typeof window === 'undefined') return <></>; before the return component trigger a new issue Error: Hydration failed because the initial UI does not match what was rendered on the server.

Did you manage to solve this @foufrix ? Have the same issue, it also clobbers fast-refresh