Skip to content
Advertisement

bufferGeometry setFromPoints with react-three-fiber

Considering toLinePath function:

const toLinePath = (arrayOfPoints, color = 0x000000) => {
  const path = new THREE.Path();
  const firstPoint = arrayOfPoints[0];

  path.moveTo(firstPoint.x, firstPoint.y, firstPoint.z);
  arrayOfPoints.forEach(point => path.lineTo(point.x, point.y, point.z));
  path.closePath();

  const points = path.getPoints();
  const geometry = new THREE.BufferGeometry().setFromPoints(points);
  const material = new THREE.LineBasicMaterial({ color });
  const line = new THREE.Line(geometry, material);
  return line;
};

I want to recreate it using react-three-fiber and been trying something like this:

import React from 'react'
import * as THREE from 'three'
import ReactDOM from 'react-dom'
import { Canvas } from 'react-three-fiber'

function LinePath(props) {
  const vertices = React.useMemo(() => {
    const path = new THREE.Path()
    const firstPoint = props.vertices[0]

    path.moveTo(firstPoint.x, firstPoint.y, firstPoint.z)
    props.vertices.forEach(point => path.lineTo(point.x, point.y, point.z))
    path.closePath()

    return path.getPoints()
  }, [props.vertices])

  return (
    <line>
      <bufferGeometry attach="geometry" setFromPoints={vertices} />
      <lineBasicMaterial attach="material" color="black" />
    </line>
  )
}


ReactDOM.render(
  <Canvas>
    <LinePath vertices={[new THREE.Vector3(0, 0, 0), new THREE.Vector3(2, 2, 0), new THREE.Vector3(-2, 2, 0)]} />
  </Canvas>,
  document.getElementById('root')
)

But there’s no output/error at all. I suppose I’ve completely misunderstood react-three-fibers API. What am I doing wrong here? Thanks and here’s the sandbox

Advertisement

Answer

For a future googler, useUpdate has been removed here:

https://github.com/pmndrs/react-three-fiber/pull/996.

Use useLayoutEffect instead.

 const ref = React.useRef<BufferGeometry>(null!);
  useLayoutEffect(() => {
    if (ref.current) {
      ref.current.setFromPoints(points);
    }
  }, []);

  return (
    <line>
      <bufferGeometry attach='geometry' ref={ref} />
      <lineBasicMaterial color={0xff0000} />
    </line> 
  );
Advertisement