Getting startedReact tutorial

Updating presence

On the previous page we learned to set up presence with an initial value of { cursor: null }—let’s learn how to update presence by taking this and turning it into realtime cursors.

Updating

To get cursor location we can use browser PointerEvents. Switch to Room.tsx and add a function for onPointerMove that gets your cursor location using clientX/clientY and updates your current presence with the value.

Modify the code in /Room.tsx
// Update cursor coordinates on pointer movefunction handlePointerMove(e) {  const cursor = { x: Math.floor(e.clientX), y: Math.floor(e.clientY) };  updateMyPresence({ cursor });}

Next, create a function for onPointerLeave that sets the cursor value to null.

Modify the code in /Room.tsx
// Set cursor to null on pointer leavefunction handlePointerLeave(e) {  updateMyPresence({ cursor: null });}

And finally, make sure that our div element spans the screen, add the two events.

Modify the code in /Room.tsx
return (  <div    style={{ width: "100vw", height: "100vh" }}    onPointerMove={handlePointerMove}    onPointerLeave={handlePointerLeave}  >    Cursor: {JSON.stringify(myPresence.cursor)}  </div>);

If you hover over a preview window, you’ll now see the coordinates of your cursor, taken from myPresence! On the next page we’ll use this to render the cursors.

We use cookies to collect data to improve your experience on our site. Read our Privacy Policy to learn more.