Code Monkey home page Code Monkey logo

react-three-next's Introduction

Downloads Discord Shield

🏯 React-Three-Next starter

A minimalist starter for NextJS, @react-three/fiber and Threejs.

  • TTL ~ 100ms
  • First load JS ~Β 79kb
  • Lighthouse score of 100 (Performance, Accessibility, Best Practices, SEO)

This starter allows you to navigate seamlessly between pages with dynamic dom and/or canvas content without reloading or creating a new canvas every time. 3D components are usable anywhere in the dom. The events, dom, viewport, everything is synchronized!

⚫ Demo :

image

How to use

Installation

Tailwind is the default style. styled-components (styled) are also available.

yarn create r3f-app next my-app
# yarn create r3f-app <next> my-app <tailwind|styled>? -ts?
# npx create-r3f-app next my-app

πŸ›‚ Typescript

For typescript add the parameter -ts or --typescript:

yarn create r3f-app next my-app -ts
# npx create-r3f-app next my-app -ts

πŸ—» Features

  • GLSL imports
  • Canvas is not getting unmounted while navigating between pages
  • Canvas components usable in any div of the page
  • Based on the App directory architecture
  • PWA Support

πŸš„ Architecture

Thanks to tunnel-rat the starter can portal components between separate renderers. Anything rendered inside the <View/> component of the starter will be rendered in the 3D Context. For better performances it uses gl.scissor to cut the viewport into segments.

<div className='relative'>
  <View orbit className='relative sm:h-48 sm:w-full'>
    <Dog scale={2} />
    // Some 3D components will be rendered here
  </View>
</div>

πŸŽ›οΈ Available Scripts

  • yarn dev - Next dev
  • yarn analyze - Generate bundle-analyzer
  • yarn lint - Audit code quality
  • yarn build - Next build
  • yarn start - Next start

⬛ Stack

How to contribute :

git clone https://github.com/pmndrs/react-three-next
&& cd react-three-next && yarn install

Maintainers :

react-three-next's People

Contributors

agcty avatar alaricbaraou avatar allcontributors[bot] avatar dbismut avatar dependabot-preview[bot] avatar drcmda avatar dylantackoor avatar ecklf avatar emalorenzo avatar exitsimulation avatar fackux avatar jhsu avatar johnathan-aretos avatar johnphamous avatar jorgevv avatar modster avatar mszekiel avatar nissan avatar njm222 avatar renaudrohlinger avatar sachinraja avatar saravieira avatar shuta13 avatar suttonjack avatar winstonrc avatar yct37785 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-three-next's Issues

Why store router on zustand if router is already available via useRouter?

I'm curious about what's the advantage / goal of storing router on zustand if it's already available via useRouter ?

const router = useRouter()
useEffect(() => {
useStore.setState({ router })
}, [router])

const router = useStore((state) => state.router)

const router = useStore((s) => s.router)

Broken install with styled components

yarn create r3f-app next my-app-2 styled -ts

yarn create v1.23.0-20220130.1630
warning package.json: No license field
[1/4] πŸ”  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] πŸ”—  Linking dependencies...
warning "create-r3f-app > [email protected]" has unmet peer dependency "@babel/preset-env@^7.1.6".
[4/4] πŸ”¨  Building fresh packages...
success Installed "[email protected]" with binaries:
      - create-r3f-app
Welcome. Project's generation started using create-R3F-App 🐱
> πŸš€ Creating my-app-2 using r3f-next-starter...

Cloning into 'my-app-2'...
remote: Enumerating objects: 2091, done.
remote: Counting objects: 100% (64/64), done.
remote: Compressing objects: 100% (47/47), done.
remote: Total 2091 (delta 26), reused 48 (delta 17), pack-reused 2027
Receiving objects: 100% (2091/2091), 2.10 MiB | 0 bytes/s, done.
Resolving deltas: 100% (1160/1160), done.
> Success! Folder and files created for my-app-2

> Installing packages...

> Success! Installed dependencies for my-app-2

> Installing packages for styled-components...

> Success! Installed dependencies for styled-components

> Installing packages for TypeScript...

> Success! Installed dependencies for TypeScript

> Initializing for styled-components...

> Generating styled-components from tailwind

> Generating styled-components from tailwind

> Generating styled-components from tailwind

> Generating styled-components from tailwind

node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: ENOENT: no such file or directory, open '/Users/r/GitHub/my-app-2/.babelrc'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/Users/r/GitHub/my-app-2/.babelrc'
}

Node.js v18.3.0
error Command failed.
Exit code: 1
Command: /usr/local/bin/create-r3f-app
Arguments: next my-app-2 styled -ts
Directory: /Users/r/GitHub
Output:

Is there a way to turn off canvas for specific pages?

Is it possible to turn off (or remove) the canvas for specific pages?
I'm trying to have a plain React page that is scrollable, but if I just overlay the DOM component over Canvas, I can't scroll the page down as the height is fixed to the window height.

Consider using Next.js page properties

First of all thanks for the great starter. Truly streamlined to get things running with Next.js despite my limited understanding of Three.js.

Having said that, I find the approach inside _app.js to be rather unusual for a Next.js application, as this all could be achieved with Next.js page properties - or is there something I'm missing here?

The following works great and, unlike the current approach, works out of the box with normal Next.js pages:

/src/pages/index.tsx

import dynamic from 'next/dynamic'

import Instructions from '@/components/dom/Instructions'

const Shader = dynamic(() => import('@/components/canvas/Shader/Shader'), {
  ssr: false,
})

const Page = () => {
  return <Instructions />
}

Page.r3f = <Shader />

export default Page

export async function getStaticProps() {
  return {
    props: {
      title: 'Index',
    },
  }
}

/src/pages/_app.tsx

import { useRouter } from 'next/router'
import useStore from '@/helpers/store'
import { useEffect } from 'react'
import Header from '@/config'
import Dom from '@/components/layout/dom'
import '@/styles/index.css'
import dynamic from 'next/dynamic'

const LCanvas = dynamic(() => import('@/components/layout/canvas'), {
  ssr: false,
})

import type { AppProps } from 'next/app'
import type { NextPage } from 'next'

type NextPageWithR3F = NextPage & {
  r3f?: React.ReactNode
  title: string
}

type AppPropsWithR3F = AppProps & {
  Component: NextPageWithR3F
}

function App({ Component, pageProps }: AppPropsWithR3F) {
  const router = useRouter()

  useEffect(() => {
    useStore.setState({ router })
  }, [router])

  return (
    <>
      <Header title={pageProps.title} />
      <Dom>
        <Component {...pageProps} />
      </Dom>
      <LCanvas>{Component?.r3f}</LCanvas>
    </>
  )
}

export default App

Broken demo in development mode

Hello, I created an app using this command
yarn create r3f-app next my-app styled -ts

Then in the index page it says that if i click de box it should go to the box page, but it doesnt. Also the events like onPointerOver and onPointerOut are not getting called.

Finally when I start the app in development mode it display this warning on the vscode terminal.

(node:16492) [DEP_WEBPACK_SINGLE_ENTRY_PLUGIN] DeprecationWarning: SingleEntryPlugin was renamed to EntryPlugin (Use "node --trace-deprecation ..." to show where the warning was created) Defining routes from exportPathMap (node:16492) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated. BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.

Cannot find module error

Template: yarn create r3f-app next my-app -ts

module-err
Cannot find module 'module'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?

tsconfig.json:
err-2
Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.

Adding "moduleResolution": "node" in tsconfig.json fixes the issue

Intall gets an error

Hi ,
When I try to install I will get an error.
yogesh@yogi:~/Dev$ yarn create r3f-app next my-app -ts
yarn create v1.22.11
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
warning "create-r3f-app > [email protected]" has unmet peer dependency "@babel/preset-env@^7.1.6".
[4/4] Building fresh packages...
success Installed "[email protected]" with binaries:
- create-r3f-app
[####################################################################################################################################################################################################] 347/347/home/yogesh/.config/yarn/global/node_modules/create-r3f-app/bin/create-r3f-app:22
appStyle = style ?? 'tailwind';
^

SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
error Command failed.
Exit code: 1
Command: /home/yogesh/.yarn/bin/create-r3f-app
Arguments: next my-app -ts
Directory: /home/yogesh/Dev
Output:

info Visit https://yarnpkg.com/en/docs/cli/create for documentation about this command.
read.md

read.md

styled-components setup missing proper babel config

Per the s-c docs, babel-plugin-styled-components needs a babel config, and because it will override Next's babel config, we'll need to include the next/babel preset.

minimally, .babelrc should be this:

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", {"ssr": true}]]
}

ssr: true since Next is made for SSR (although, it may be true by default?)

Note that adding a babel config will force Next 12 to use babel to transpile instead of SWC, which may be undesirable for some folks. Until Next ports it all over, which it seems it is currently working on, it has to be this way for styled-components + Next 12.

Happy to submit a PR if you point me in the right direction!

(ps. Thanks for making this starter! Really helped me out)

Production build error

Steps to reproduce:

  • yarn create r3f-app next my-app -ts
  • cd my-app
  • yarn build
  • yarn start

Captura de Pantalla 2022-09-28 a las 12 46 25

Render issue with multiple shaderMaterial

Using multiple shaderMaterial seems to have an error.

I initialized a project with yarn create r3f-app next my-app styled -ts and everything seems working fine.
But when I duplicate the Shader folder and name the corresponding fields (Shader -> Shader2, ColorShiftMaterial -> ColorShiftMaterial2) and add the component to index.jsx, the second material turns white.

Seems that the material is not initialized properly, because meshRef.current.material.uniforms turn out to be undefined.

image

Remove cross-env

https://github.com/yarnpkg/berry/tree/master/packages/yarnpkg-shell

"A JavaScript implementation of a bash-like shell"

  • Portable across systems
  • Supports variables
touch .yarnrc.yml
yarn set version berry
yarn plugin import interactive-tools

.yarnrc.yml

enableGlobalCache: true

enableTelemetry: false

nmHoistingLimits: none

nodeLinker: node-modules

packageExtensions:
  "troika-three-text@*":
    peerDependencies:
      "three": "*"

plugins:
  - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
    spec: "@yarnpkg/plugin-interactive-tools"
#  - path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
#    spec: "@yarnpkg/plugin-workspace-tools"

pnpMode: strict

preferInteractive: true

yarnPath: .yarn/releases/yarn-berry.cjs

Disable canvas mouse on dom hover !

I have GUI panels on dom where i push and scroll buttons.
But the 3d canvas is moveing and zooming at the same time.
Any ideas ? thanks up front !

Loadable error when trying to use GLTF model

Hello, first, thank you for such an awesome starter for Next! I'm currently running into an issue when trying to load a GLTF component generated from GLTFJSX. I'm trying to use this model currently and import it similar to the default Sphere. However, upon loading I keep getting this error no matter the model I try to load:

image

Any ideas on what might be causing this? You can see my current code here. I was able to load the model on a Gatsby R3F starter which leads me to thinking this is NextJS specific. Any help is greatly appreciated! πŸ™

Cannot add OrbitControl from drei to this starter.

I try to add the OrbitControl from Drei to this project. With next-transpile-modules setup, the same code works well if I create the next.js project then import react-three-fiber, drei, etc. but I cannot make it work with this template.
Here is how I edit the _canvas.jsx file. I'm I missing something?
https://codesandbox.io/s/bold-monad-dqfr3?file=/src/components/layout/_canvas.jsx:0-1402

import { Canvas, useFrame } from '@react-three/fiber'
import { Preload } from '@react-three/drei'
import { A11yUserPreferences } from '@react-three/a11y'
import useStore from '@/helpers/store'
import { OrbitControls } from '@react-three/drei'
import React, { useRef, useState } from 'react'

function Box(props) {
  // This reference will give us direct access to the THREE.Mesh object
  const mesh = useRef()
  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false)
  const [active, setActive] = useState(false)
  // Subscribe this component to the render-loop, rotate the mesh every frame
  useFrame((state, delta) => (mesh.current.rotation.x += 0.01))
  // Return the view, these are regular Threejs elements expressed in JSX
  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? 1.5 : 1}
      onClick={(event) => setActive(!active)}
      onPointerOver={(event) => setHover(true)}
      onPointerOut={(event) => setHover(false)}
    >
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  )
}

const LCanvas = ({ children }) => {
  return (
    <Canvas>
      <ambientLight />
      <pointLight position={[10, 10, 10]} />
      <Box position={[-1.2, 0, 0]} />
      <Box position={[1.2, 0, 0]} />
      <OrbitControls />
    </Canvas>
  )
}

export default LCanvas

ERR_REQUIRE_ESM when trying to use @react-three/xr with react-three-next

I am trying to add VR functionality to a project that uses react-three-next.

Just trying to import the VRCanvas with the line:

import { VRCanvas } from '@react-three/xr'

Fails with the error: ERR_REQUIRE_ESM
Must use import to load ES Module: /.../app/node_modules/three/examples/jsm/loaders/GLTFLoader.js

I tried using next-transpile-modules to load @react-three/xr but it didn't work.
And also tried using the new next.js experimental ESM feature ( { esmExternals: "loose" } ) in next.config.js without success.

Am i missing something?
Is this a problem with how react-three/xr is built?

Does anyone has an idea on how to make them work?

Thanks

`yarn create r3f-app next my-app -ts` install error

hey! thanks for the great codebase!

after running the yarn create r3f-app next my-app -ts command im getting this error. seems like we need to install yarn add --dev @types/react to be able to use typescript.

Screen Shot 2022-04-15 at 11 06 54 AM

please let me know if you need any clarification, thanks!

Issue running yarn create r3f-app

I have node v16.3.1, yarn: v1.22.17 installed an tried running the command below
yarn create r3f-app next next-remotion styled -ts node
and get error below. Any ideas I can try to resolve this? Thanks!
I
Screen Shot 2022-01-15 at 12 41 49 PM

Module '"zustand/shallow"' has no exported member 'shallow'.

I tried both the js and ts templates, in the typescript template in the src/helpers/store.ts I get the following error:

Module '"zustand/shallow"' has no exported member 'shallow'. Did you mean to use 'import shallow from "zustand/shallow"' instead?ts(2614)

In the javascript version the error doesn't exist. When I remove the braces to change from named import to default import the error disappears. Can try to do PR if you like. Thanks for the awesome work

How to use ScrollControls

The DOM is outside the Canvas so I can't wrap it in ScrollControls. I'm not sure how to handle scrolling for the canvas and DOM otherwise? Do I just pass a scroll progress value to the canvas and update the camera as I scroll through the page?

Index is remounting

Expected Behavior

The /pages/index should only mount once.

Current Behavior

The top level /pages/index is mounting twice. This is causing useEffect's that are meant to run once, run twice due to a remount.

Steps to Reproduce

  1. yarn create r3f-app next doubleLoad
  2. cd doubleLoad
  3. In index.jsx, add a useEffect, example.
useEffect(() => {
    console.log('load')
  }, []);
  1. Observe that console logs twice.

Repo example: https://github.com/qwertypants/double-load-issue
Screen Shot 2022-01-15 at 1 47 17 PM

Test Issue

ignore this. I am just testing the github webhook integration with discord :)

Error in dev mode

when running yarn dev this error occurs

(node:23899) [DEP_WEBPACK_SINGLE_ENTRY_PLUGIN] DeprecationWarning: SingleEntryPlugin was renamed to EntryPlugin
(Use `node --trace-deprecation ...` to show where the warning was created)
Defining routes from exportPathMap
(node:23899) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.```

Connecting DOM Events on trigger

Hi,
this might not be r3f specific, but maybe you can help me out.
In the src/components/layout/canvas.jsx there is this part that I don't understand.

const LCanvas = ({ children }) => {
    const dom = useStore((state) => state.dom) //Make dom-element available from Zustand store
return(
<>
  <Canvas
    mode='concurrent'
    style={{
      position: 'absolute',
      top: 0,
    }}
    onCreated={(state) => state.events.connect(dom.current)} // How does this work?
  >
</>
)
}
export default LCanvas

Where does the state.events.connect function come from?

I am asking because I want to implement a state, where the events do not pass through the dom layer anymore. How would I be able to toggle that?

texture not loading

screen becomes white when using any texture loader i.e useTexture,useLoader

prob1

after uncommenting useTexture() hook

prob2

Minimal Starter

This is just some feedback, feel free to close it.

The current starter, while very pretty while running, is quite complex for a starter. There is substantial infrastructure in place for implementing the current example demo swapping logic.

In another issue I heard that typescript was avoided to keep the starter as accessible as possible. I think the way the current "starter" basically implements a featured example showcase site is contradictory to that.

What I'm looking for in a "react-three-next" starter is the minimal amount of code to demonstrate how to integrate react-three with next since next's SSR doesn't make that straightforward. The starter should be illuminating that bit. It should be assumed that I can take it from there. I think the current code is better as a more sophisticated example project.

As it stands, I'm spending a bunch of time figuring out exactly how and what I can delete from the current starter to actually start what I'm trying to work on.

I really do like the code and the site is beautiful but I just feel it's counter to the spirit of a starter.

Browser not automatically refreshing

Hi guys,

Thanks for your boilerplate three/next js project.

I'm experiencing some issues that the browser is not automatically refreshing after a code change. Here is a short video about it:
[https://www.loom.com/share/e505126aeec24b1a8e3d3212200ba061]

I use format on save and this normally works well. I tested it with a plain next js project ("yarn create next-app" and later "yarn dev") and didn't encounter any problem with the browser refreshing himself.

Do you have any advice on how to fix this?

FYI: I consider myself still a junior developer and it's the first time I come in contact with three js, webpack and tailwind. So it might be a dumb mistake on my environment.

"GenerateSW has been called multiple times" error when running in dev mode

This is a fresh clone of the latest commit.
This also causes a service error when visiting the webpack server in the browser.

image

$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
> [PWA] Compile client (static)
> [PWA] Auto register service worker with: /Users/annazhang/git/3d-nft/3d-nft/node_modules/next-pwa/register.js
> [PWA] Service worker: /Users/annazhang/git/3d-nft/3d-nft/.next/sw.js
> [PWA]   url: /sw.js
> [PWA]   scope: /
> [PWA] Build in develop mode, cache and precache are mostly disabled. This means offline support is disabled, but you can continue developing other functions in service worker.
> [PWA] Compile server
> [PWA] Compile server
event - compiled client and server successfully in 2.8s (1021 modules)
wait  - compiling / (client and server)...
warn  - GenerateSW has been called multiple times, perhaps due to running webpack in --watch mode. The precache manifest generated after the first call may be inaccurate! Please see https://github.com/GoogleChrome/workbox/issues/1790 for more information.
warn  - GenerateSW has been called multiple times, perhaps due to running webpack in --watch mode. The precache manifest generated after the first call may be inaccurate! Please see https://github.com/GoogleChrome/workbox/issues/1790 for more information.
wait  - compiling /404 (client and server)...
warn  - GenerateSW has been called multiple times, perhaps due to running webpack in --watch mode. The precache manifest generated after the first call may be inaccurate! Please see https://github.com/GoogleChrome/workbox/issues/1790 for more information.```

question: zustand persist middleware

Hello,

I tried to persist the store's data with this middleware solution: https://github.com/pmndrs/zustand#persist-middleware

but I get a Converting circular structure to JSON error in every useEffect that sets the state

Does anyone know why this is happening?

From the past merged PRs in zustand it seems like this was worked on recently

Here is an example stack trace:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'HTMLDivElement'
    |     property '__reactFiber$7h6sih73en9' -> object with constructor 'FiberNode'
    --- property 'stateNode' closes the circle
    at stringify (<anonymous>)
    at eval (middleware.js?926f:87)
    at setItem (middleware.js?926f:146)
    at Function.api.setState (middleware.js?926f:157)
    at eval (_app.jsx?434a:51

Npx install error

Hi there ! New to r3f, i wanted to try it with NextJS.
Seems like npx create-r3f-app next not working properly.

When installing :

Welcome. Project's generation started using create-R3F-App 🐱
> πŸš€ Creating next-r3f using r3f-next-starter...

Cloning into 'next-r3f'...
remote: Enumerating objects: 1944, done.
remote: Counting objects: 100% (646/646), done.
remote: Compressing objects: 100% (449/449), done.
remote: Total 1944 (delta 352), reused 422 (delta 171), pack-reused 1298
Receiving objects: 100% (1944/1944), 1.71 MiB | 1.26 MiB/s, done.
Resolving deltas: 100% (1079/1079), done.
←[32m> Success!←[39m Folder and files created for ←[1mnext-r3f←[22m

> Installing packages...

←[31m> Error!←[39m npm installation failed

> Initialized a git repository.

> ←[32mAwesome!←[39m You're now ready to start coding.

  I already ran ←[1mnpm install←[22m for you, so your next steps are:
    ←[1mcd next-r3f←[22m

  To start a local server for development:
    ←[1mnpm run dev←[22m

  To build a version for production:
    ←[1mnpm run build←[22m

  To run the server in production:
    ←[1mnpm run start←[22m

  Questions? Feedback? Please let me know!
  ←[32mhttps://github.com/RenaudRohlinger/create-r3f-app/issues←[39m

npm install :

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/webpack
npm ERR!   dev webpack@"^5.61.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@"^4.19.1" from [email protected]
npm ERR! node_modules/next-offline
npm ERR!   dev next-offline@"^5.0.5" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

current node version : 16.13.0
current npm version : 8.1.4

Any ideas on how to solve the problem ?

Trouble upgrading to next 12

When I upgrade to next 12 I encounter the following error on build:

event - compiled successfully in 476 ms (871 modules)
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check your code at _app.jsx:42.
    at ForwardPropsToR3fComponent (webpack-internal:///./src/pages/_app.jsx:67:3)
    at UserContextProvider (webpack-internal:///./src/utils/useUser.js:28:54)
    at App (webpack-internal:///./src/pages/_app.jsx:108:3)
    at StyleRegistry (/Users/chasedavis/Documents/meshbg/node_modules/styled-jsx/dist/stylesheet-registry.js:231:34)
    at AppContainer (/Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/render.js:325:29)
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
    at ReactDOMServerRenderer.render (/Users/chasedavis/Documents/meshbg/node_modules/react-dom/cjs/react-dom-server.node.development.js:4053:17)
    at ReactDOMServerRenderer.read (/Users/chasedavis/Documents/meshbg/node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29)
    at Object.renderToString (/Users/chasedavis/Documents/meshbg/node_modules/react-dom/cjs/react-dom-server.node.development.js:4298:27)
    at Object.renderPage (/Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/render.js:621:45)
    at Object.defaultGetInitialProps (/Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/render.js:301:51)
    at Function.getInitialProps (webpack-internal:///./node_modules/next/dist/pages/_document.js:187:16)
    at Object.loadGetInitialProps (/Users/chasedavis/Documents/meshbg/node_modules/next/dist/shared/lib/utils.js:69:29)
    at renderDocument (/Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/render.js:634:48)
    at Object.renderToHTML (/Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/render.js:673:34)
    at async doRender (/Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/next-server.js:1389:38)
    at async /Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/next-server.js:1484:28
    at async /Users/chasedavis/Documents/meshbg/node_modules/next/dist/server/response-cache.js:63:36

My naive assumption is that the next.config.js needs an update, as it seems like under the hood there are some curly braces missing when trying to load the export default App from _app.jsx

EDIT:

It looks like I may be experiencing this issue and I also receive the following error in dev tool
Screen Shot 2021-11-05 at 3 05 14 PM
s

R3F components fall over if only pass one child component into "Page" component in <page>.tsx

I tried starting off my codebase by cloning /pages/box.tsx and /canvas/Box.tsx. Let's say my new component is called "Shape". In /pages/shape.tsx, I changed the Page component to only have , and not .

This meant that at this line: https://github.com/pmndrs/react-three-next/blob/main/src/pages/_app.jsx#L37, the child.length > 1 check fails, and so renders the Component without wrapping it in LCanvas.

Is there a good reason for this child.length > 1 check? If not, I suggest it's removed. Or mandate and document that all /pages/<page>/tsx files must provide at least one DOM and one R3F component, though this would be a weird requirement I think.

Can't install `npx create-r3f-app next my-app` error

I'm trying to install the starter, I'm running npx create-r3f-app next my-app -ts

and receiving the error

    appStyle = style ?? 'tailwind';
                      ^

SyntaxError: Unexpected token '?'
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11

I'm running npm 7.22.0

Anyone else facing this issue?

Problem when installing - "next not found"

Hi,

I'm trying to install react-three-next
When installation. I'm following the steps:

$ npx create-r3f-app next my-app
$ cd my-app
$ npm run dev

And it returns the next:

> [email protected] dev
> next dev

sh: 1: next: not found

So inside of my-app I did:

> npm install

and it returns:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"^18.0.0-alpha-dbe3363cc" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@">=17.0" from @react-three/[email protected]
npm ERR! node_modules/@react-three/fiber
npm ERR! @react-three/fiber@"^7.0.6" from the root project
npm ERR! peer @react-three/fiber@">=6.0" from @react-three/[email protected]
npm ERR! node_modules/@react-three/a11y
npm ERR! @react-three/a11y@"^2.1.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/spacecomet/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/spacecomet/.npm/_logs/2021-09-01T20_21_29_342Z-debug.log

Any ideas why this happens. I'm not able to use this package...

Unable to run npm install

After cloning the project, when running npm install, the following output occurs:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/eslint
npm ERR!   dev eslint@"^8.20.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer eslint@"^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" from [email protected]
npm ERR! node_modules/eslint-plugin-tailwind
npm ERR!   dev eslint-plugin-tailwind@"^0.2.1" from the root project

Warning in dev mode

Used ts template to create project

yarn create r3f-app next my-app -ts

run yarn dev

In terminal we get

warn  - Invalid next.config.js options detected: 
[
  {
    "instancePath": "",
    "schemaPath": "#/additionalProperties",
    "keyword": "additionalProperties",
    "params": {
      "additionalProperty": "webpackDevMiddleware"
    },
    "message": "must NOT have additional properties"
  },
.
.
.

] 
See more info here: https://nextjs.org/docs/messages/invalid-next-config
> [PWA] PWA support is disabled
> [PWA] PWA support is disabled

Just a warning, dev server seems to work fine

image not show when loaded in next but working in react

When i load the model in next the image it contains does not appear, no errors showing in console.

The model is mac-draco

Any ideas on how to debug or solve?

IMG_2061

import * as THREE from 'three'
import { Suspense, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Canvas, useFrame, useLoader } from '@react-three/fiber'
import { Environment, useGLTF } from '@react-three/drei'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { useSpring } from '@react-spring/core'
import { a as three } from '@react-spring/three'
import { a as web } from '@react-spring/web'
import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger'

const vec = new THREE.Vector3()

export default function Mac() {
  // This flag controls open state, alternates between true & false
  const [open, setOpen] = useState(false)
  // We turn this into a spring animation that interpolates between 0 and 1
  const props = useSpring({ open: Number(open) })
  const [hinge, setHinge] = useState(1.575) // to -0.425
  const macReference = useRef()

  useLayoutEffect(() => {
    gsap.registerPlugin(ScrollTrigger)

    ScrollTrigger.create({
      trigger: macReference.current,
      start: 'center-=20% center',
      // endTrigger: '.macEnd',
      end: 'center+=20% center',
      // markers: true,
      onEnter: () => setOpen(true),
      onLeaveBack: () => setOpen(false),
      onUpdate: self => setHinge(1.575 + self.progress * (-0.425 - 1.575))
    })
  }, [])

  return (
    <div className="relative h-full laptopContent" ref={macReference}>
      <web.main
        style={{ background: props.open.to([0, 1], ['#f4f7ff', '#87a1a9']) }}
      >
        <Canvas
          // dpr={[1, 2]}
          camera={{ position: [0, 0, 0], fov: 35 }}
          className="laptopSection"
        >
          <three.pointLight
            position={[10, 10, 10]}
            intensity={1.5}
            color={props.open.to([0, 1], ['#e7efee', '#d25578'])}
          />
          {/* eslint-disable-next-line unicorn/no-null */}
          <Suspense fallback={null}>
            <group
              rotation={[0, Math.PI, 0]}
              onClick={event => {
                event.stopPropagation()
                setOpen(!open)
              }}
            >
              <Model
                open={open}
                // hinge={props.open.to([0, 1], [1.575, -0.425])}
                hinge={hinge}
              />
            </group>
            <Environment preset="city" />
          </Suspense>
        </Canvas>
      </web.main>
      <span className="macEnd" />
    </div>
  )
}

function Model({ open, hinge, ...props }) {
  const group = useRef()
  // Load model
  const root = useGLTF('/mac-draco.glb')
  console.log('πŸš€ ~ file: Mac.js ~ line 92 ~ Model ~ root', root)

  const colorMap = useLoader(TextureLoader, 'PavingStones092_1K_Color.jpg')

  const { nodes, materials } = root

  // Take care of cursor state on hover
  const [hovered, setHovered] = useState(false)
  useEffect(
    // eslint-disable-next-line no-return-assign, no-void
    () => void (document.body.style.cursor = hovered ? 'pointer' : 'auto'),
    [hovered]
  )
  // Make it float in the air when it's opened
  useFrame(state => {
    const t = state.clock.getElapsedTime()
    state.camera.position.lerp(vec.set(0, 0, open ? -24 : -32), 0.1)
    state.camera.lookAt(0, 0, 0)
    group.current.rotation.x = THREE.MathUtils.lerp(
      group.current.rotation.x,
      // open ? Math.cos(t / 2) / 8 + 0.25 : 0,
      open ? Math.cos(t / 2) / 8 + 0.25 : 0,
      0.1
    )
    group.current.rotation.y = THREE.MathUtils.lerp(
      group.current.rotation.y,
      open ? Math.sin(t / 4) / 4 : 0,
      0.1
    )
    group.current.rotation.z = THREE.MathUtils.lerp(
      group.current.rotation.z,
      open ? Math.sin(t / 4) / 4 : 0,
      0.1
    )
    group.current.position.y = THREE.MathUtils.lerp(
      group.current.position.y,
      open ? (-2 + Math.sin(t)) / 3 : -4.3,
      0.1
    )
  })
  // The view was auto-generated by: https://github.com/pmndrs/gltfjsx

  return (
    <group
      ref={group}
      {...props}
      onPointerOver={event => {
        event.stopPropagation()
        setHovered(true)
      }}
      onPointerOut={() => setHovered(false)}
      dispose={undefined}
    >
      <three.group rotation-x={hinge} position={[0, -0.04, 0.41]}>
        <group position={[0, 2.96, -0.13]} rotation={[Math.PI / 2, 0, 0]}>
          <mesh
            material={materials.aluminium}
            geometry={nodes.Cube008.geometry}
          />
          <mesh
            material={materials['matte.001']}
            geometry={nodes.Cube008_1.geometry}
          />
          <mesh
            material={materials['screen.001']}
            geometry={nodes.Cube008_2.geometry}
          />
        </group>
      </three.group>
      <mesh
        material={materials.keys}
        geometry={nodes.keyboard.geometry}
        position={[1.79, 0, 3.45]}
      />
      <group position={[0, -0.1, 3.39]}>
        <mesh
          material={materials.aluminium}
          geometry={nodes.Cube002.geometry}
        />
        <mesh
          material={materials.trackpad}
          geometry={nodes.Cube002_1.geometry}
        />
      </group>
      <mesh
        material={materials.touchbar}
        geometry={nodes.touchbar.geometry}
        position={[0, -0.03, 1.2]}
      />
    </group>
  )
}

// useGLTF.preload('/mac-draco.glb')

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.