supermedium / aframe-react

:atom: Build virtual reality experiences with A-Frame and React.
https://ngokevin.github.io/aframe-react-boilerplate/
MIT License
1.42k stars 151 forks source link

Some components cannot be used until React Component is mounted #52

Closed jsantell closed 7 years ago

jsantell commented 7 years ago

When adding a raycaster and cursor component (to represent an <a-cursor>) to an entity, the element gets created before mounted to the DOM, causing the raycaster component's this.el.sceneEl to be undefined (as it has yet to be mounted), throwing an error and causing the scene to fail to render. A work around is to wait until the component is mounted to DOM and then adding more components, but this took some time to figure out. Similar to assumptions in #50 of when things are mounted and initialized, I wonder if there's a general way of handling this for all components.


import React, { Component, PropTypes } from 'react';
import { Entity } from 'aframe-react';

class CameraComponent extends Component {
  constructor() {
    super();
    this.state = {
      mounted: false,
    };
  }

  componentDidMount() {
    this.setState({ mounted: true });
  }

  render() {
    const mountedProps = {};

    if (this.state.mounted) {
      mountedProps.cursor = 'maxDistance: 100; fuse: true; fuseTimeout: 1000'
    };

    return (
      <Entity id='camera-container' {...this.props}>
        <Entity camera>
          <Entity
            {...mountedProps}
            raycaster='objects: .action'    
            geometry='primitive: plane'>
          </Entity>
        </Entity>
      </Entity>
    );
  }
};

export default CameraComponent;
ngokevin commented 7 years ago

That's weird since A-Frame won't try to execute the components until the entity is mounted.

jsantell commented 7 years ago

This is also after the a-scene's loading event is fired, if it helps

ngokevin commented 7 years ago

OK thanks, got a lot of maintenance lined up for aframe-react :)

jsantell commented 7 years ago

~Looks like an aframe issue, filed aframevr/aframe#2225~

Looks like I was wrong about that bug being related here, that example does not inject the component within an a-scene

ngokevin commented 7 years ago

v4.0.x should solve since .setAttribute()s are called on the ref, which is after mount. Will add unit tests though.

ngokevin commented 7 years ago

Added unit test for wrapped entity. https://github.com/ngokevin/aframe-react/commit/44bee27c36c5d20762a2b6f3d068927a0ea14df8

Didn't see any errors in the log. Should work now since everything is initialized only once after the ref is attained. In other words, after mount.