Fork me on GitHub
#clojurescript
<
2022-07-09
>
stagmoose09:07:15

If I want to rewrite this react jsx syntax to cljs:

<Moveable
  onDragStart={({ target, clientX, clientY }) => {
                console.log("onDragStart", target);
            }}
/>
I know that { target, clientX, clientY } is the destruction of props, and I tried this (but fail):
(fn [{:keys [target clientX clientY]}] (js/console.log "onDragStart" target))
the value in console is onDragStart null so the destruction in clojure way didn't seem to work. How could I fix this?

stagmoose09:07:14

I've checked https://github.com/madvas/jsx-to-clojurescript for inspiration but didn't find something relavant.

Hermann08:07:28

My guess is that the event arrives as a JS-Object instead of a Clojure-Map, so you'll need to access elements using dot syntax (fn [event] (prn (.-target event)))

Hermann08:07:22

Or to destructure (fn [event] (let [{:keys [target]} (js->clj event)] ...))

stagmoose13:07:19

thanks, thomas has answered that in the next thread.

thheller09:07:08

destructuring with :keys expects a clojure map-like thing as they are looked up by keyword which JS properties are not

thheller09:07:45

can't really do this with destructuring, but (fn [^js obj] (.-target obj) (.-clientX obj) (.-clientY obj)) works. the ^js hint is to aid externs inference

stagmoose09:07:51

yeah. it's working know!!! Thanks for your help as always~

stagmoose09:07:48

@U05224H0W is it a common practice to use js->clj to convert the object then do destructing? Although I find the result of js->clj is like this (the keys of that map is string instead of keyword)

{"datas" {}, "moveable" #object[MoveableManager [object Object]], "currentTarget" #object[MoveableManager [object Object]], "clientY" 136, "setTransformIndex" #object[setTransformIndex], "clientX" 197, "inputEvent" #object[MouseEvent [object MouseEvent]], "target" #object[HTMLDivElement [object HTMLDivElement]], "set" #object[set], "setTransform" #object[setTransform]}

p-himik09:07:25

Don't use js->clj for something you have no control over, unless there's a guarantee it will remain a plain object/array. js->clj doesn't work for custom JS classes. Also, js->clj will be much slower than simple field access via interop. It doesn't always matter, but often it does.

🙏 1
stagmoose09:07:57

@U2FRKM4TW okay, thanks for your information!

chrisetheridge08:07:18

if you do want destructuring for JS objects (and other nice JS utilities) there's https://github.com/applied-science/js-interop

🙏 1
stagmoose09:07:34

wow, this is cool!