Im new to React Three Fiber I am trying to tie a simple event click to the 4 geometries rendered in this project. I can not figure out how to assign an event to each individual Hex geometry render . The idea is that when it is clicked a tooltip, model or even console.log alert will pop up and show which object was clicked by assigning it a number i.e. 1,2,3,4.
I'm not sure where to start with building an iterative object to tie to each click event? any direction would be greatly appreciated.
here is my working code and a code sandbox: Code SandBox ThreeFiber! https://codesandbox.io/s/serene-fermi-g61kn?file=/src/App.js
import React, { useRef, useState } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import PropTypes from "prop-types";
function Hex(props) {
// This reference will give us direct access to the mesh
const mesh = useRef();
// Set up state for the hovered and active state
const [hovered, setHover] = useState(false);
const [active, setActive] = useState(false);
// Rotate mesh every frame, this is outside of React without overhead
useFrame(() => {
mesh.current.rotation.x = mesh.current.rotation.y += 0.01;
});
return (
<mesh
{...props}
ref={mesh}
scale={active ? 2 : 1}
onClick={(e) => setActive(!active || console.log("This box was clicked"))}
// onClick={(e) => { if (window.confirm('You Selected box # 1')) this.setActive(!active) } }
onPointerOver={(e) => setHover(true)}
onPointerOut={(e) => setHover(false)}
>
<sphereGeometry args={[1, 8, 5]} />
<meshStandardMaterial color={hovered ? 0x49ef4 : 0x10e5dc} />
</mesh>
);
}
// Not working at this point getting a simple tooltip or console log would suffice???
// class Modal extends React.Component {
// onClose = e => {
// this.props.onClose && this.props.onClose(e);
// };
// render() {
// if (!this.props.show) {
// return null;
// }
// return (
// <div class="modal" id="modal">
// <h2>This is Three fiber</h2>
// <div class="content">{this.props.children}</div>
// <div class="actions">
// <button class="toggle-button" onClick={this.onClose}>
// close
// </button>
// </div>
// </div>
// );
// }
// }
// Modal.propTypes = {
// onClose: PropTypes.func.isRequired,
// show: PropTypes.bool.isRequired
// };
export default function App() {
return (
<Canvas style={{ height: 300, background: "000000", width: 500 }}>
<ambientLight intensity={0.5} />
<spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} />
<pointLight position={[-10, -10, -10]} />
{/* <Modal/> to to activate pop up when sphere is clicked*/}
// console.log when event click#1
<Hex position={[-1.5, 0, 0]} />
// console.log when event click#2
<Hex position={[1.5, 0, 0]} />
// console.log when event click#3
<Hex position={[0, -1.5, 0]} />
// console.log when event click#4
<Hex position={[0, 1.5, 0]} />
</Canvas>
);
}