Skip to content

Dat.gui

Import

import { GUI } from 'dat.gui'

Description

Using Dat.GUI with React Three Fiber.

Dat.gui has been a trusted micro UI for vanilla JavaScript projects across the web for many years.

It is good to know that it can also be used in your R3F applications.

We can install Dat.GUI from its official repository.

npm install dat.gui --save-dev

And optionally, if you need the type definitions,

npm install @types/dat.gui --save-dev

Add the import to your script.

import { GUI } from 'dat.gui'

And in your component, you can create and use it in a useEffect.

function Box({ gui }) {
  const ref = useRef()

  useEffect(() => {
    const gui = new GUI()
    gui.add(ref.current.rotation, 'x', 0, Math.PI * 2)
    gui.add(ref.current.rotation, 'y', 0, Math.PI * 2)
    gui.add(ref.current.rotation, 'z', 0, Math.PI * 2)
    return () => {
      gui.destroy()
    }
  }, [])

  return (
    <mesh ref={ref}>
      <boxGeometry />
      <meshBasicMaterial color={0x00ff00} wireframe />
    </mesh>
  )
}

Be sure to destroy the GUI, as shown in the above example, in case the component JSX is ever refreshed. Otherwise, you could have multiple GUIs instantiated into your document.

Working Example

<>

Sharing Dat.GUI Among Several Components

The above example is great if only one of your components need the Dat.GUI and you can create it complete in the useEffect.

Below is an example where each component manages its own folder within one shared Dat.GUI.

Working Example

<>

Some examples using Dat.GUI

Squircle sbcode.net
Displacement Map sbcode.net
Object3D Hierarchy sbcode.net
Modify Geometry Attribute sbcode.net

Comments