Context issues with React and requestAnimationFrame - reactjs

I'm currently playing around with React and Three.js. I'm trying to call an update function that is passed as a prop to another component as below. The problem is I get an error sayign this.cube is undefined.
public renderer : THREE.WebGLRenderer;
public scene : THREE.Scene = new THREE.Scene();
public camera : THREE.PerspectiveCamera = new THREE.PerspectiveCamera(70, 400 / 300, 0.1, 0.1);
public cube : THREE.Mesh;
public componentDidMount() {
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
this.cube = new THREE.Mesh(geometry, material);
this.scene.add(this.cube);
}
public update = () => {
console.log(this);
console.log(this.cube);
this.cube.rotation.x += 0.01;
this.cube.rotation.y += 0.01;
}
public render() {
const sceneArr : THREE.Scene[] = [];
sceneArr.push(this.scene);
return (
<React.Fragment>
<Three mainCamera={this.camera} width={400} height={300} update={this.update} scenes={sceneArr} />
</React.Fragment>
);
}
Here is the render function inside the `Three` component calling `requestAnimationFrame`.
public threeRender = () => {
this.props.update();
requestAnimationFrame(this.threeRender);
this.props.scenes.forEach(scene => {
this.renderer.render(scene, this.props.mainCamera);
});
}
I assumed that the context of this inside update was incorrectly referring to the Three component, but it turns out that the print statements inside update showed contradicting evidence.
console.log(this) returns the correct object context, and the cube member shows up in the log, but console.log(this.cube) returns undefined. This makes no sense to me. Any ideas?

Inside of your constructor initialize cube and then you should be able to refer to it without getting that error.
constructor(props){
this.cube = {}
}
Now you can give this.cube a value and refer to it from within update()

Related

Update texture of mesh using ThreeJS & Dat.Gui

I would like the texture of my Mesh to update when clicked on function.
When you click on the 'UpdateMateria' function i'd like the mesh to dispose its current texture and add a new one.
Animation Loop
startAnimationLoop = () => {
const tableBoard = this.scene.getObjectByName('tableSurface');
tableBoard.material.map = this.updateMateria;
this.renderer.render(this.scene, this.camera);
this.requestID = window.requestAnimationFrame(this.startAnimationLoop);
};
Dat.Gui
userGUI = () => {
const update = {
updateMateria: function() {
alert('Changing');
this.material.dispose();
this.material.map = texture1();
}
}
this.gui = new dat.GUI();
const controls = function() {
this.title = new controls();
this.gui.add(update, 'updateMateria')
}
}
When i put the function straight into the 'Animation Loop' this actually updates the texture to the desired one, but the current version gives me 'TypeError: Cannot read property 'dispose' of undefined'
First, you can not use the this reference in updateMateria (probably updateMaterial???). Consider to safe the this reference in a variable outside of this function and use this variable instead. Besides, it's not necessary to dispose the material if you just want to change the texture.
userGUI = () => {
const scope = this;
const update = {
updateMateria: function() {
alert('Changing');
// scope.material.dispose();
scope.material.map = texture1();
}
}
this.gui = new dat.GUI();
const controls = function() {
this.title = new controls();
this.gui.add(update, 'updateMateria')
}
three.js R108

How do I create an ag-Grid cell editor using React and TypeScript?

I see that the ag-grid-react repo has types, and I also see that the ag-grid-react-example repo has examples. But how do I put the two together and create a cell editor with React and Types?
I'm guessing it's something like this but I can't make TypeScript happy:
class MyCellEditor implements ICellEditorReactComp {
public getValue() {
// return something
}
public render() {
const { value } = this.props
// return something rendering value
}
}
I implemented ICellEditor and used ICellEditorParams for prop definitions. For example, this MyCellEditor example from their documentation:
// function to act as a class
function MyCellEditor () {}
// gets called once before the renderer is used
MyCellEditor.prototype.init = function(params) {
// create the cell
this.eInput = document.createElement('input');
this.eInput.value = params.value;
};
// gets called once when grid ready to insert the element
MyCellEditor.prototype.getGui = function() {
return this.eInput;
};
// focus and select can be done after the gui is attached
MyCellEditor.prototype.afterGuiAttached = function() {
this.eInput.focus();
this.eInput.select();
};
// returns the new value after editing
MyCellEditor.prototype.getValue = function() {
return this.eInput.value;
};
// any cleanup we need to be done here
MyCellEditor.prototype.destroy = function() {
// but this example is simple, no cleanup, we could
// even leave this method out as it's optional
};
// if true, then this editor will appear in a popup
MyCellEditor.prototype.isPopup = function() {
// and we could leave this method out also, false is the default
return false;
};
became this:
class MyCellEditor extends Component<ICellEditorParams,MyCellEditorState> implements ICellEditor {
constructor(props: ICellEditorParams) {
super(props);
this.state = {
value: this.props.eGridCell.innerText
};
}
// returns the new value after editing
getValue() {
// Ag-Grid will display this array as a string, with elements separated by commas, by default
return this.state.value;
};
// Not sure how to do afterGuiAttached()
// if true, then this editor will appear in a popup
isPopup() {
return true;
};
render() {
return (
<div>
hello
</div>
);
}
}

React function not recognized

In my react app, I have an onClick function that isn't being recognized (TypeError: _this2.click is not a function) when called from dynamically-generated components. I poked around for issues with functions not being bound correctly, but they seem to be. Here's the code:
class C extends React.Component {
constructor(props) {
super(props);
// Bind components
this.eventComponent = this.eventComponent.bind(this);
this.click = this.click(this);
}
/**
* Click function for when a user selects their choice
* #param {[int]} id [id of the event the user is selecting]
*/
click(id) {
console.log(id)
}
/**
* Draws an event component (dynamically generated)
* #param {[String]} name [name of the event]
* #param {[String]} summary [summary of event]
* #return {[Object]} [react element of an event]
*/
eventComponent(name, summary, id) {
if (name != null && summary != null) {
return (
<div >
<h1>{name}</h1>
<p>{summary}</p>
<button onClick={() => this.click(id)}>Here is a button!</button>
</div>
);
}
}
render() {
var event = this.state.event
var objArray = this.state.objArray
var eventMap;
if (event) {
eventMap = objArray.map(function(event) {
// Get first property
var firstProp;
var k;
for(var key in event) {
if(event.hasOwnProperty(key)) {
firstProp = event[key];
k = key;
break;
}
}
return this.eventComponent(firstProp.title, firstProp.summary, k);
}.bind(this))
} else {
eventMap = <p>No events found!</p>;
}
// Generate a default HTML object
var eventComponent = (
<div>
{eventMap}
</div>
);
return eventComponent;
}
}
in your constructor correct this this.click = this.click(this);
to this.click = this.click.bind(this);
The most easy and convenient way is to use arrow functions, so you don't need to do binding in constructor anymore, a lot easier, isn't it?
so just remove this from constructor:
this.click = this.click.bind(this);
and change your function to:
click = (id) => {
console.log(id)
}
As answered by Vikas,
either you can follow that approach or you can use arrow syntax for functions using which there will be no need to bind functions.
Eg.
Click = (Id) => {
} .

How to use Babylonjs in Reactjs Application?

I have tried import babylonjs in react but its is not working. Does any body know how to import and use the babylonjs in reactjs application.
Thanks.
Not sure if you have found the answer on your own, however there are several ways now as babylon has matured. There is actually a Node package for using babylon.js with react here: https://www.npmjs.com/package/react-babylonjs
Also there is an install guide for React in Babylon.js in the docs:
https://doc.babylonjs.com/resources/babylonjs_and_reactjs
Hope that helps!
Babylon JS is available as npm package. You can easily build a simple React Component around a canvas and Babylon JS
I have created a minimal example with React+ Babylon:
/* Babylon JS is available as **npm** package.
You can easily build a simple `React` Component around a `canvas` and Babylon JS
I have created a minimal example with React+ Babylon:
*/
import React, { Component } from "react";
import * as BABYLON from "babylonjs";
var scene;
var boxMesh;
/**
* Example temnplate of using Babylon JS with React
*/
class BabylonScene extends Component {
constructor(props) {
super(props);
this.state = { useWireFrame: false, shouldAnimate: false };
}
componentDidMount = () => {
// start ENGINE
this.engine = new BABYLON.Engine(this.canvas, true);
//Create Scene
scene = new BABYLON.Scene(this.engine);
//--Light---
this.addLight();
//--Camera---
this.addCamera();
//--Meshes---
this.addModels();
//--Ground---
this.addGround();
// Add Events
window.addEventListener("resize", this.onWindowResize, false);
// Render Loop
this.engine.runRenderLoop(() => {
scene.render();
});
//Animation
scene.registerBeforeRender(() => {
boxMesh.rotation.y += 0.01;
boxMesh.rotation.x += 0.01;
});
};
componentWillUnmount() {
window.removeEventListener("resize", this.onWindowResize, false);
}
onWindowResize = event => {
this.engine.resize();
};
/**
* Add Lights
*/
addLight = () => {
//---------- LIGHT---------------------
// Create a basic light, aiming 0,1,0 - meaning, to the sky.
var light = new BABYLON.HemisphericLight(
"light1",
new BABYLON.Vector3(0, 10, 0),
scene
);
};
/**
* Add Camera
*/
addCamera = () => {
// ---------------ArcRotateCamera or Orbit Control----------
var camera = new BABYLON.ArcRotateCamera(
"Camera",
Math.PI / 2,
Math.PI / 4,
4,
BABYLON.Vector3.Zero(),
scene
);
camera.inertia = 0;
camera.angularSensibilityX = 250;
camera.angularSensibilityY = 250;
// This attaches the camera to the canvas
camera.attachControl(this.canvas, true);
camera.setPosition(new BABYLON.Vector3(5, 5, 5));
};
/**
* Create Stage and Skybox
*/
addGround = () => {
// Create a built-in "ground" shape.
var ground = BABYLON.MeshBuilder.CreateGround(
"ground1",
{ height: 6, width: 6, subdivisions: 2 },
scene
);
var groundMaterial = new BABYLON.StandardMaterial("grass0", scene);
groundMaterial.diffuseTexture = new BABYLON.Texture(
"./assets/ground.jpeg",
scene
);
ground.material = groundMaterial;
//Add SkyBox
var photoSphere = BABYLON.Mesh.CreateSphere("skyBox", 16.0, 50.0, scene);
var skyboxMaterial = new BABYLON.StandardMaterial("smat", scene);
skyboxMaterial.emissiveTexture = new BABYLON.Texture(
"assets/skybox.jpeg",
scene,
1,
0
);
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.emissiveTexture.uOffset = -Math.PI / 2; // left-right
skyboxMaterial.emissiveTexture.uOffset = 0.1; // up-down
skyboxMaterial.backFaceCulling = false;
photoSphere.material = skyboxMaterial;
};
/**
* Add Models
*/
addModels = () => {
// Add BOX
boxMesh = BABYLON.MeshBuilder.CreateBox(
"box",
{ height: 1, width: 1, depth: 1 },
scene
);
boxMesh.position.y = 1;
var woodMaterial = new BABYLON.StandardMaterial("wood", scene);
woodMaterial.diffuseTexture = new BABYLON.Texture(
"./assets/portal_cube.png",
scene
);
boxMesh.material = woodMaterial;
};
render() {
return (
<canvas
style={{ width: window.innerWidth, height: window.innerHeight }}
ref={canvas => {
this.canvas = canvas;
}}
/>
);
}
}
export default BabylonScene;
Live Demo:
https://codesandbox.io/s/babylonjs-react-template-w2i1k

Angular 2 observable doesn't 'map' to model

As I'm learning Angular 2 I used an observable to fetch some data via an API. Like this:
getPosts() {
return this.http.get(this._postsUrl)
.map(res => <Post[]>res.json())
.catch(this.handleError);
}
My post model looks is this:
export class Post {
constructor(
public title: string,
public content: string,
public img: string = 'test') {
}
The problem I'm facing is that the map operator doesn't do anything with the Post model. For example, I tried setting a default value for the img value but in the view post.img displays nothing. I even changed Post[] with an other model (Message[]) and the behaviour doesn't change. Can anybody explain this behaviour?
I had a similar issue when I wanted to use a computed property in a template.
I found a good solution in this article:
http://chariotsolutions.com/blog/post/angular-2-beta-0-somnambulant-inauguration-lands-small-app-rxjs-typescript/
You create a static method on your model that takes an array of objects and then call that method from the mapping function. In the static method you can then either call the constructor you've already defined or use a copy constructor:
Mapping Method
getPosts() {
return this.http.get(this._postsUrl)
.map(res => Post.fromJSONArray(res.json()))
.catch(this.handleError);
}
Existing Constructor
export class Post {
// Existing constructor.
constructor(public title:string, public content:string, public img:string = 'test') {}
// New static method.
static fromJSONArray(array: Array<Object>): Post[] {
return array.map(obj => new Post(obj['title'], obj['content'], obj['img']));
}
}
Copy Constructor
export class Post {
title:string;
content:string;
img:string;
// Copy constructor.
constructor(obj: Object) {
this.title = obj['title'];
this.content = obj['content'];
this.img = obj['img'] || 'test';
}
// New static method.
static fromJSONArray(array: Array<Object>): Post[] {
return array.map(obj => new Post(obj);
}
}
If you're using an editor that supports code completion, you can change the type of the obj and array parameters to Post:
export class Post {
title:string;
content:string;
img:string;
// Copy constructor.
constructor(obj: Post) {
this.title = obj.title;
this.content = obj.content;
this.img = obj.img || 'test';
}
// New static method.
static fromJSONArray(array: Array<Post>): Post[] {
return array.map(obj => new Post(obj);
}
}
You can use the as keyword to de-serialize the JSON to your object.
The Angular2 docs have a tutorial that walks you through this. However in short...
Model:
export class Hero {
id: number;
name: string;
}
Service:
...
import { Hero } from './hero';
...
get(): Observable<Hero> {
return this.http
.get('/myhero.json')
.map((r: Response) => r.json() as Hero);
}
Component:
get(id: string) {
this.myService.get()
.subscribe(
hero => {
console.log(hero);
},
error => console.log(error)
);
}

Resources