Skip to main content

Example 5 - Hooks & Stores

This shows an example of how to modify the viewer state via its exposed hooks.

Hooks are Zustand stores that can be used to access and modify the state of the viewer.

See stores for more information.

Reference: Example 5 - Hooks & Stores

Key Features

/* eslint-disable i18next/no-literal-string */

import { Button } from "@mui/material";
import { useState } from "react";

import { PlySample, SingleSTL } from "../../data/scans";
import { CameraUtils } from "../../helpers/CameraUtils";
import { useObjects } from "../../stores/useObjects";
import { Viewport } from "../../ui/Viewport";
import { Viewer } from "../../Viewer";
import { PerspectiveView } from "../../views/PerspectiveView";

const factoryPath = PlySample["FACTORY"].url;
const scanPath = SingleSTL["SCAN"].url;

function App() {
return (
<Viewer
sx={{
background: "transparent",
position: "absolute",
inset: 0,
zIndex: 0,
}}
objects={{
example: {
url: scanPath,
},
}}
>
<ToggleButton />

<Viewport
sx={{
background: "transparent",
position: "absolute",
inset: 0,
zIndex: 0,
}}
props={{}}
name={"3d"}
component={PerspectiveView}
/>
</Viewer>
);
}

function ToggleButton() {
const [currentObjectIdx, setCurrentObjectIdx] = useState(0);
const objects = [factoryPath, scanPath];

// With these hooks it's possible to modify the viewer state with your custom components.
const setObjects = useObjects((s) => s.setObjects);

function handleObjectsChange() {
setCurrentObjectIdx((currentObjectIdx + 1) % objects.length);
setObjects({
example: {
url: objects[currentObjectIdx],
},
});

// Recenter the views after changing the object.
// You can also pass an angle to the recenter function to rotate the view.
CameraUtils.recenterAllViews();
}

return (
<Button
onClick={handleObjectsChange}
sx={{
position: "absolute",
top: "1rem",
left: "1rem",
zIndex: 10,
}}
>
Toggle objects
</Button>
);
}

export default App;