Files
a2e3b27dfc Migrate the with-jotai example from page router to app router (#63390)
## Migrate the with-jotai example from page router to app router

Please if it needs further updates, Let me know!
Happy to contribute

---------

Co-authored-by: Sam Ko <[email protected]>
2024-03-18 21:28:29 +00:00

58 lines
1.3 KiB
TypeScript

"use client";
import { atom, useAtom } from "jotai";
type Point = [number, number];
const dotsAtom = atom<Point[]>([]);
const drawingAtom = atom<boolean>(false);
const handleMouseDownAtom = atom(null, (get, set) => {
set(drawingAtom, true);
});
const handleMouseUpAtom = atom(null, (get, set) => {
set(drawingAtom, false);
});
const handleMouseMoveAtom = atom(
(get) => get(dotsAtom),
(get, set, update: Point) => {
if (get(drawingAtom)) {
set(dotsAtom, (prev) => [...prev, update]);
}
},
);
const SvgDots = () => {
const [dots] = useAtom(handleMouseMoveAtom);
return (
<g>
{dots.map(([x, y], index) => (
<circle cx={x} cy={y} r="2" fill="#aaa" key={index} />
))}
</g>
);
};
export default function Canvas() {
const [, handleMouseUp] = useAtom(handleMouseUpAtom);
const [, handleMouseDown] = useAtom(handleMouseDownAtom);
const [, handleMouseMove] = useAtom(handleMouseMoveAtom);
return (
<svg
width="100vw"
height="100vh"
viewBox="0 0 100vw 100vh"
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseMove={(e) => {
handleMouseMove([e.clientX, e.clientY - 150]);
}}
>
<rect width="100vw" height="100vh" fill="#eee" />
<SvgDots />
</svg>
);
}