react-three-fiber react-three-fiber react-three-fiber

Pointer events

Using pointer events with a mesh for mouseover and click interactions. Fork on Codesandbox

Live example


Coming Soon

Code

import React, { useRef, useState } from "react";
import ReactDOM from "react-dom";
import { Canvas, useFrame } from "react-three-fiber";
import { OrbitControls } from "@react-three/drei";
import "./styles.css";

const Box = (props) => {
  const boxRef = useRef();
  const [active, setActive] = useState(false);
  const [hover, setHover] = useState(false);

  useFrame(() => {
    if (hover) {
      boxRef.current.rotation.y += 0.05;
    }
  });

  return (
    <group ref={boxRef} position={props.position}>
      <mesh
        onClick={() => {
          setActive(!active);
        }}
        onPointerOver={() => {
          setHover(true);
        }}
        onPointerOut={() => {
          setHover(false);
        }}
      >
        <boxGeometry attach="geometry" />
        <meshLambertMaterial
          attach="material"
          color={active ? "green" : "red"}
        />
      </mesh>
    </group>
  );
};

const App = () => {
  return (
    <Canvas
      style=
      camera=
    >
      <ambientLight intensity={0.1} />
      <pointLight position={[5, 5, 5]} />
      <Box />
      <OrbitControls />
    </Canvas>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

Running this example

Clone this repo, and then NPM install and NPM start from the relevant directory.

$ cd examples/other/pointer-events
$ npm install && npm run start