Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2".

Encountering the following error:

Error: class constructors must be invoked with 'new'
    Call Stack:
    renderWithHooks
    mountIndeterminateComponent
    beginWork
    callCallback
    ...
    

The errors are associated with components such as <BoxGeometry>, <MeshPhysicalMaterial>, and <ForwardRef(Canvas)>.

Below is the code for Lab2.js route:


    import { Canvas } from "@react-three/fiber";
    import Floor from "../components/floor";

    function Lab2() {
        return(
            <div className="w-screen h-screen">
                <Canvas
                shadows={true}
                className="bg-slate-500"
                camera={{
                    position: [-6, 7, 7],
                }}>
                    <Floor position={[0, -1, 0]} />
                </Canvas>
            </div>
        );
    }

    export default Lab2;

And the floor.js component:


    import { BoxBufferGeometry, MeshPhysicalMaterial } from "three";

    function Floor(props) {
        return (
            <mesh {...props} recieveShadow={true}>
                <BoxBufferGeometry args={[20,1,10]} />
                <MeshPhysicalMaterial color='white' />
            </mesh>
        );
    }

    export default Floor;

List of dependencies and versions:


    "dependencies": {
        "@react-three/fiber": "^8.0.27",
        "next": "12.1.6",
        "react": "18.2.0",
        "react-dom": "18.2.0",
        "three": "^0.141.0"
      },
      "devDependencies": {
        "autoprefixer": "^10.4.7",
        "eslint": "8.18.0",
        "eslint-config-next": "12.1.6",
        "postcss": "^8.4.14",
        "tailwindcss": "^3.1.4"
      }
    

If anyone can offer guidance, it would be highly appreciated.

Answer №1

When using React-Three-Fiber, there is no need to import BoxBufferGeometry and MeshPhysicalMaterial from the three library if you simply want to include them in the jsx component similarly to how you don't import mesh. All you have to do is convert these to camel-case as shown below:

function Floor(props) {
    return (
        <mesh {...props} receiveShadow={true}>
            <boxBufferGeometry args={[20,1,10]} />
            <meshPhysicalMaterial color='white' />
        </mesh>
    );
}

export default Floor;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for efficiently transferring a retrieved object from App.js to a child component in ReactJS version 16 and above using asynchronous methods

TL;DR How can I pass a fetched object from App.js to a child component asynchronously? Do I need to wait for the data to be completely fetched before returning App.js? If so, how can I achieve this? In an attempt to create a dashboard using react-chartj ...

Unable to eliminate the beforeunload event

The code below is used to display a default pop-up when the page is refreshed or closed: var myEvent = window.attachEvent || window.addEventListener; var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, ...

When using res.render to send results, redundant lines are displayed

I feel like I must be missing something really obvious, but for the life of me I cannot figure out what it is. All I want to do is list the documents in a MongoDB collection in a straightforward manner. I am working with nodejs, mongoose, and Jade (althoug ...

Passing props to component data in Vuejs: Best practices

I'm experimenting with Vue 2.0 and I've encountered a bit of confusion. How can I properly pass props to a component's internal data? I've followed the documentation, but it still seems unclear. HTML <service-list :services="model"& ...

Having trouble with IE7 - unable to interact with elements below popup form

<script type="text/javascript">var switchTo5x=true;</script> <script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script> <script type="text/javascript">stLight.options({publisher:'b42661f5-2dc5 ...

Is XMLHttpRequest just sitting idle...?

As a newcomer to the world of javascript and AJAX, I've been stuck on a single problem for the past 8 hours. Despite my best efforts, I just can't seem to figure out what's going wrong. On my website, I have an image with an onclick event ca ...

Obtain the JSON object by provided criteria

In the given JSON data, how can I access an object based on the provided applicationName? { "apps": [ { "applicationName": "myTestApp", "keys": [ { "key": "app-key", ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

Using Next.js: Invoking router.push once the API await statement is resolved

I find myself in a bit of a conundrum here, so bear with me as I try to explain the situation: So, I've got these two pages - Page 1 and Page 2. Page 1 houses a document that needs approval, hence the presence of an "Approve" button. This Approve but ...

The Cordova Network Information Plugin is experiencing some functionality issues

I successfully developed a Mobile application using Cordova, Onsen UI, and Vue.js. While addressing network connectivity issues, I incorporated the cordova plugin cordova plugin add cordova-plugin-network-information For determining the type of connectio ...

What are the implications of an unidentified callback function with parameters?

Check out this snippet: const fs = require('fs'); fs.readFile('foo.txt', 'utf8', (error, data) => { if (error) { throw new Error(error); } console.log(data); }); Can you figure out where the anonymous callback is recei ...

Guide on updating individual rows in Google App Script using data from a different sheet

I am trying to create a script that will pull a value from column[3] in the ZONE sheet to the active sheet, specifically in column 56 of the job sheet when the zonelist value matches the zone value in different sheets. The script should check the range fro ...

Seeking a regular expression to identify special characters appearing at the beginning of a string

I'm looking to update my current regex pattern to include special characters at the beginning of a string value. Here's what I have right now: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+.]{ ...

Limiting the zoom in three.js to prevent object distortion caused by the camera

I'm currently in the process of developing a three.js application where I have successfully loaded my STL objects and incorporated 'OrbitControls'. However, I am encountering an issue when attempting to zoom using the middle scroll button on ...

Protect an API endpoint without requiring credentials

I have a form that verifies if an email is already in my database (/api/[email protected]), and if so, it provides their information. I am struggling to find a method to secure my API routes from individuals using tools like Postman to repeatedly att ...

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Is it possible to use the AngularJS function with the <div> HTML element?

I am facing an issue with displaying a modal when clicking on a <div> element. The function assigned to show the modal by changing the CSS property 'display' from 'none' to 'block' works fine when attached to a button, b ...

Failed to load the SWC binary in the subsequent attempt

Encountering an error when attempting to execute the command for nextjs npm run dev, with a message indicating failure to load SWC binary. More information can be found here: https://nextjs.org/docs/messages/failed-loading-swc. I have attempted uninstalli ...

Troubleshooting unexpected issues with dynamically updating HTML using innerHTML

Need help with a renderWorkoutUpdated function that replaces specific workout records with updated values. _renderWorkoutUpdated(currentWorkout) { let html = `<li class="workout workout--${currentWorkout.type}" data-id="${ curre ...

Include criteria in my ajax call (conditional statements)

Is there a way to add conditions to my ajax request? Whenever I include the code below, it only seems to work for one item at a time. $.ajax({ type: 'GET', url: urlPost, success: function (data) { $.each(data, function (key, value) { ...