React Three Fiber encountered an unexpected JSON token 'c' at position 3

I am encountering an issue while trying to load a .glb file using react-three-fiber. The error I'm receiving is as follows:

Error Unexpected token c in JSON at position 3

I can't seem to figure out what mistake I am making - it seems that the common solution to this problem is to have the .glb file in the public folder (which I have done). So, I'm confused about where the problem lies.

Below is the link to the codesandbox:

https://codesandbox.io/s/gltfloader-forked-5nkzl?file=/src/App.js

Here is the code snippet:

import "./styles.css";
import { Suspense } from "react";
import { Canvas, useLoader } from "@react-three/fiber";
import { Environment, OrbitControls } from "@react-three/drei";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";


const Model = () => {
 const gltf = useLoader(GLTFLoader, './scene.glb');
  return (
  <>
  <primitive object={gltf.scene} scale={0.4} />
</>
);
};

export default function App() {
 return (
  <div className="App">
  <Canvas>
    <Suspense fallback={null}>
      <Model />
      <OrbitControls />
      <Environment preset="sunset" background />
    </Suspense>
  </Canvas>
</div>
);
}

If anyone could provide any assistance, it would be greatly appreciated.

Answer №1

The path ./scene.glb is not valid. Fetching from relative paths is not allowed in general. To resolve this issue, you can either move scene.glb to the /public directory and reference it as /scene.glb, or import sceneUrl from "./scene.glb". The unexpected token error you are experiencing is due to Three.js loader receiving a 404 response.

Answer №2

Using the sceneUrl import should do the trick.

import "./styles.css";
import { Suspense } from "react";
import { Canvas, useLoader } from "@react-three/fiber";
import { Environment, OrbitControls } from "@react-three/drei";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";

// Importing sceneUrl
import sceneUrl from './scene.glb'


const Model = () => {
 const gltf = useLoader(GLTFLoader, sceneUrl);
  return (
  <>
  <primitive object={gltf.scene} scale={0.4} />
</>
);
};

export default function App() {
 return (
  <div className="App">
  <Canvas>
    <Suspense fallback={null}>
      <Model />
      <OrbitControls />
      <Environment preset="sunset" background />
    </Suspense>
  </Canvas>
</div>
);
}

Answer №3

After struggling with an issue for a couple of days, I finally found a solution.

All it took was using the npm package npx gltfjsx [Model.js] [options].

Simply execute the command

npx gltfjsx [your model name here .glb]
and watch as it creates a jsx file for you.

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

Mastering the art of utilizing clearInterval effectively

This reset button needs to clear/reset the timer. The issue is that when the user presses the start button more than once, it sets two timers - one from the previous start and one from the current start. I will be using clearInterval to solve this problem ...

Encountering an issue while trying to import the instanceMethods function within Sequelize

In a file, I have written a function and exported it like this: export function foo(params...) { // do something } When initializing the model, I imported the function in the following manner: import { foo } from "../path/..." instanceMethods: { foo ...

Understanding the functionality of an array as an index in JavaScript

It was discovered (tested in Chrome) that the index of an array can actually be an array itself: a = [1, 2, 3] index = [1] a[index] // returns 2 Has there been any official documentation confirming this behavior? ...

Understanding special characters within a URL

Here is a URL example: postgres://someuser:pas#%w#@rd-some-db.cgosdsd8op.us-east-1.rds.amazonaws.com:5432 This URL is being parsed using the following code snippet: const url = require('url'); const { hostname: host, port, auth, path } = url.par ...

Upon logging in to the first HTML page, the user will be automatically redirected to the second HTML page while passing values

Is there a way to automatically redirect users to Login2.html when selecting "TEAM" in the dropdown on Login1.html, using the values entered in Login1.html? Similarly, can we redirect them to the Premium page when they select "Premium"? I need a solution u ...

Encountering NaN values in JavaScript arrays

I'm facing an issue with my HTML code that is supposed to make ball(s) bounce around the canvas. However, when I set the arrays storing the coordinates to random positions and test with alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));, it retur ...

Having trouble getting your Ajax script to function correctly when submitting a form?

I am currently facing an issue where I am loading a partial page, but I do not want the form on this page to redirect when the save button is clicked. I am unsure if I am using the script correctly. I would like to post to the controller when the submit b ...

Having trouble dynamically displaying the '<' symbol using JavaScript?

Whenever I attempt to show a string with the character '<' in it, the part of the string that comes after the symbol is not displayed. Strangely enough, when I output it to the console, it appears correctly. Take a look at this excerpt showcas ...

Transforming a JavaScript Date object to a Java LocalDateTime

In my current project, I am facing a challenge while attempting to pass UTC time from a JavaScript front end to a Java backend. My initial approach involved utilizing the Date.toISOString() method and sending the generated object to the Java backend. Howev ...

How does combineReducers in Redux determine which specific portion of the application state to send to the reducer?

While going through the Redux basics tutorial, I found myself a bit confused about how the code snippet below determines which part of the application state should be passed to each reducer mentioned in the combineReducers function. Does it simply rely o ...

Titanium: Warning upon initiation

Is it feasible to trigger an alert immediately after a window finishes loading? I am using a create window function followed by an alert message, then returning. function NewView() { var self = Ti.UI.createWindow({}); alert("A basic or confirm al ...

Steps to retain localStorage data while redirecting to another external webpage

Encountering an issue with saving localStorage data across redirects. See the code snippet below: // Invoke newSitelogin(). Save response(credentials) in localStorage. Redirect to new URL. newSitelogin({ uuid, password }) .then(() => { window.ope ...

The default expansion behavior of Google Material's ExpansionPanel for ReactJS is not working as expected

Currently, I am in the process of developing a ReactJS application that utilizes Google's Material-UI. Within this project, there is a child class that gets displayed within a Grid once a search has been submitted. Depending on the type of search con ...

Determine whether the browser tab is currently active or if the user has switched to a different

Is there a way to detect when a user switches to another browser tab? This is what I currently have implemented: $(window).on("blur focus", function (e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // handle double fir ...

How can you gather user data on a website without relying on a database and making it voluntary?

In order to streamline the process, the user should be able to send a preformatted email with the click of a button or have their data stored securely without leaving the site. The goal is to avoid the extra step of using a mailto: link, unless the email c ...

Passing events from a grandchild component up to its grandparent component in VueJS 2.0

Vue.js 2.0 appears to have a limitation where events cannot be emitted directly from a grand child component to its grand parent. Vue.component('parent', { template: '<div>I am the parent - {{ action }} <child @eventtriggered="pe ...

Three.js experiencing issues with FBX animations running erratically

Having trouble with animations on some fbx models. When an animation lasts 20 seconds, the model remains stationary for 19 seconds and then suddenly moves within the last second or so. However, other fbx models animate correctly. The code used to run the a ...

Ways to create a fixed button positioned statically at the bottom of a page

Currently, I am utilizing tailwind CSS to create a webpage with Next and Back buttons for navigation. However, an issue arises when there is minimal content on the page as the button adheres to the top. For visual reference, please view the image linked be ...

Smoothly cycle material colors in separate THREE.js geometries

Hello everyone! Check out the codepen I provided for a multiple curves animation. My goal is to achieve a smooth hue change at every drawn curve. Each subsequent curve should have a slightly shifted hue, and I want to be able to control the duration of th ...

Utilizing jQuery to retrieve data from a JSON object with a nested array

After making an API call to Google Translate, the following data was returned: { "data": { "detections": [ [ { "language": "en", "isReliable": false, "confidence": 0.051902372 } ] ] } } In order to access the "language" ...