The error message "TypeError: element.setAttribute is not a function" occurred in the context of React Native and Three

Struggling with implementing drei (a collection of helpers for react three fiber) on Android / Expo devices. While it works fine on web browsers, the device consistently throws an Exception error:

TypeError: element.setAttribute is not a function. (In 'element.setAttribute(eventName, 'return;')', 'element.setAttribute' is undefined)

The issue can be traced back to line 321 in \node_modules\metro\src\lib\polyfills\require.js This specific line reads:

factory(

            global,
            metroRequire
            metroImportDefault,

Facing this problem while utilizing the default code:

import React, { useRef, useState } from "react";
import { StyleSheet, View } from "react-native";
import { Canvas, useFrame } from "react-three-fiber";
import { Sky } from '@react-three/drei'; // triggering the error


function Box(props) {
  // This reference provides direct access to the mesh
  const mesh = useRef();

  // State management for hover and activate states
  const [hovered, setHover] = useState(false);
  const [active, setActive] = useState(false);

  // Mesh rotation per frame without React overhead
  useFrame(() => {
    if (mesh && mesh.current) {
      mesh.current.rotation.x = mesh.current.rotation.y += 0.01;
    }
  });

  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? [1.5, 1.5, 1.5] : [1, 1, 1]}
      onClick={(e) => setActive(!active)}
      onPointerOver={(e) => setHover(true)}
      onPointerOut={(e) => setHover(false)}
    >
      <boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
      <meshStandardMaterial
        attach="material"
        color={hovered ? "blue" : "red"}
      />
    </mesh>
  );
}

export default function App() {
  return (
    <View style={styles.container}>
      <Canvas>
        <ambientLight />
        <Sky />
        <pointLight position={[10, 10, 10]} />
        <Box position={[-1.2, 0, 0]} />
        <Box position={[1.2, 0, 0]} />
      </Canvas>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "black",
  },
});

The error occurs when using import { Sky } from '@react-three/drei', any drei reference triggers this issue. Removing it and its references enables the project to run smoothly on devices. The project functions normally on browsers even with drei.

Seeking advice or confirmation that drei may not be compatible with devices.

Answer №1

Element.setAttribute() is a method specifically used by HTMLElements. If you're curious to learn more about it, feel free to check out this resource. The functionality of this method on browsers is related to the creation and manipulation of elements such as <div> or <img>.

However, when trying to export to a device, the function may not be accessible due to limitations in capabilities.

In situations where an element is created and returns undefined, attempting to call undefined.setAttribute() will result in an error since undefined does not have this method available.

To address this issue, one potential solution could involve delving into the source code of the drei module to identify and modify the problematic section. This might require creating a modified version of the module that excludes any instances where it tries to create an HTMLElement without disrupting the overall build process.

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

Choosing attribute values from a list with jQuery

Can jQuery select multiple items at once like this: // Example $('input[name=val1 or val2 or val3...]') Currently, I am attempting to achieve the following: $("input[name='A'] input[name='B'] input[name='C']").blu ...

Tips for sending component properties to the static navigationOptions function of the react-navigation library

In my React component class, I needed to create a custom header for react-navigation that is conditionally rendered based on the props passed to the component. The issue was that I couldn't just rely on the props passed in as parameters to the route. ...

Monitoring changes in input can be a crucial step in any data analysis

Is there a way to track changes in input using backbone? How it can be achieved in AngularJs: <div ng-controller="W3"> <input type="text" ng-model="val" > <p>{{val}}</p> </div> I would like the value of the in ...

Feeling unsure about starting the project with React?

I am encountering difficulties while setting up my React project. The errors I am facing are hindering the process, and I am seeking assistance. The new React app is being created at the following location: H:\React Projects\react-js. As I try ...

Error: Child component received an undefined prop

Within my parent component, I have three child components. The first child component is a form that, upon submission, passes data to the second and third child components through props via the parent component. However, in one of the child components, the ...

Exploring the Benefits of Using AJAX with Single or Multiple JavaScript Files

Here's a question for best practices. I'm working on building an AJAX application where the main page loads everything through AJAX into the content section. Should I merge all my javascript files into one that is loaded on the main page, or spli ...

Dealing with unresolved promises in async/await functions

What is the best approach for handling unresolved promises? For instance: class Utils { static async thisFunctionOnlyResolvesWhenPassed2AndNeverRejects(number: number) { return new Promise((resolve, reject) => { if(number === 2 ...

Issue encountered while sending binary data to the server

After attempting to read a local file on the client side and sending it to the server, I encountered an error while trying to retrieve the image. JavaScript let req let rsp async function _post(url,data) { req = await fetch(url,{method: 'POST' ...

Working with Vuex: Simplifying state management by accessing multiple state objects with a single update mutation/action

I am facing a challenge with updating objects containing different strings using a single mutation and action in my project. Currently, I am attempting to extract a string from an input field's value and name, using the name as the object property to ...

Creating a universal mock object in AngularJS, specifically designed for testing with Jasmine and Karma

When it comes to unit testing, I've created a mock object that I use in my test files like this: var mockObject = { mockMethod1 : function() {return true}, mockMethod2 : function() {return true} }; beforeEach(module('myModule') , ...

Analyzing and sorting two sets of data in JavaScript

I am currently working with two arrays that are used to configure buttons. The first array dictates the number of buttons and their order: buttonGroups: [ 0, 2 ] The second array consists of objects that provide information about each button: buttons = ...

Choose a specific element based on the content of its href attribute

Hello and thank you for your assistance! In the past, I have used JavaScript to add an active class to an element based on the URL being displayed. Now, I am looking to modify this behavior. My goal is to add an active class to an element if the href att ...

Creating a JavaScript-powered multi-department form: A step-by-step guide

Is there a way to maintain the form displayed on a webpage created in HTML5 and JavaScript for logging calls across three different departments? With buttons assigned to each department, clicking on them reveals the respective HTML form. That said, every t ...

Angular constantly looping due to $watchCollection being triggered repeatedly

I am interested in monitoring the changes of an object, referred to as x, specifically its properties which are checkboxes. When a user checks a box, it alters the checked property (prop1) to 1. Each property contains certain content, and when enabled, it ...

Preventing Double Click Events on jQuery Spinner

I have been working on an option picker, but now there is a new requirement to make the options configurable. While this shouldn't be too difficult, I am facing some issues with the option picker: Currently, when an item is double-clicked, it will ge ...

React blogging site's administrative dashboard

https://i.sstatic.net/M6fUJ.png I am currently in the process of developing a blogging platform using MERN technology. Specifically, I am focused on creating a restful API with Node.js, Express, and MongoDB. The frontend, built with React, consists of thr ...

Having trouble getting jQuery click event to work with Express for loading a Handlebars page

My jQuery on click function is not working properly in conjunction with Express to route to a handlebars page and display the passed information. I have attempted different solutions such as changing the HTTP method from GET to POST, not using handlebars ...

implementing smooth scrolling using jquery following object insertion

I have a Ruby on Rails application with Bootstrap styling. Recently, I updated an object and reinserted it into the page. Now, I want to scroll to the top of a specific div with a smooth animation since I'm ordering based on the 'updated_at' ...

Ways to divide different paths within a React Application

In my index.js file, I currently have the following code: <Router routes={routes} /> I want to move the routes section to a separate file. Here's what I've tried so far: routes.js export default ( <div> <Route path= ...

React Native - "Avoid using objects as React children to prevent errors"

Issue Encountering an error when trying to import a functional component into a React class component. The error message reads: "Invariant Violation: Objects are not valid as a React child (found: object with keys {width, height, backgroundColor, textAli ...