I am trying to get the id of an object I created in react-three-fiber. I tried to use document.getElementById but have not been successful.
Here is my object I created:
const createFace = () => {
let face = [];
let size = props.cubeArr[0].length;
for (let row = 0; row < size; row++) {
let rowArr = [];
for (let col = 0; col < size; col++) {
let position = [col - 1, size - 2 - row, 0];
rowArr[col] = (
<Cell
key={`${props.side}-${row}-${col}`}
id={`${props.side}-${row}-${col}`}
position={position}
/>
);
}
face[row] = <group key={`${props.side}-${row}`}>{rowArr}</group>;
I did not include the rest of the three.js code for brevity, but essentially I am setting an id to each of my Cells and I would like to access these 3D Cells based on their ID so I can run click functions.
I found a similar question here but can't see how to translate it to react
Three.js objects have this optional property called .name. You can assign names to your Meshes, and then you can access them with .getObjectByName(). It's a clean alternative that frees you of React's sloppy useRef approach:
// First you assign a name to the object
const mesh = new THREE.Mesh(geometry, material);
mesh.name = "mySpecialMesh";
// ...
// Then later on you can find this object by the name you assigned
const sameMesh = scene.getObjectByName("mySpecialMesh");
I pressume you could do something similar with <Cell name="mySpecialMesh" />
Shortly after posting this, I found some answers that refer to using the useRef hook on my groups.
This implementation works, but not sure if its the most appropriate way of going about this. Anyways, as of now this method works
import React, {useRef} from 'react'
const Cell = (props) => {
let cellRef = useRef();
const clickSurroundingCell = (e) => {
e.stopPropagation()
let cubeObject = cellRef.current.parent.parent.parent // get main parent to check all objects
// clicking on the cell reference here
let cellToClick = cubeObject.children[0].children[0].children[0]
cellToClick.__r3f.handlers.onClick(event) // this executes the referenced cell onClick function
}
return (
<Plane onClick={clickSurroundingCell}>
</Plane>
)
}