Skip to content

Event Propagation

Working Example

<>

Description

When an event, such as a onPointerDown, onPointerOver, onPointerOut, etc., happens, the event will also propagate to its parent component and any components situated behind it in the scene under the mouse at the time of the mouse event.

In the above example, the top box, in row A, is a parent of all others beneath it. The two boxes in row B, are parents of the other boxes below them, etc.

Click any box in the working example, and you will see the boxes ancestors also light up and increasing their counter value.

To disable the propagation of events up through the hierarchy, edit the working example and uncomment the stopPropagation() line. E.g.,

function Box(props) {
  return (
    <mesh
      {...props}
      onPointerDown={(e) => {
        e.stopPropagation()
        setCount(count + 1)
      }}
      // .. other code, etc

Using stopPropagation to Stop Events from Going Behind

The stopPropagation() method can also be used to stop mouse/pointer events from effecting any meshes that may be situated behind the object being interacted with.

Without using stopPropagation() in the pointer event callbacks, then both the polygons would rotate if they were both exactly under the mouse pointer.

<>

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout eventPropagation
npm install
npm start

Comments