Fork me on GitHub
#reagent
<
2019-06-11
>
tianshu13:06:42

without ref, how to find a dom inside the component? I want focus on a input tag when a button is clicked.

oconn13:06:10

You could still do that with refs, but another option is to just use id’s and document.getElementById

tianshu14:06:43

It seems ref is not recommend by React?

tavistock14:06:27

can you link to where it says this?

lilactown14:06:08

ref is definitely recommended by React

lilactown14:06:20

but ultimately it is the same thing as passing an atom around

lilactown14:06:26

a common thing people do is this:

(defn my-form []
  (let [input-ref (r/atom nil)
        handle-click (fn [] (when @input-ref (.focus @input-ref)))]
    (fn []
      [:div
       [:button {:on-click handle-click} "Focus"]
       [:input {:ref (fn [ref] (when ref (reset! input-ref ref)))}]])))

lilactown14:06:52

what React dissuades is using “string refs”

lilactown14:06:14

which was an old API that they’ve deprecated. the ☝️ above is using callback refs, which are definitely supported

tianshu15:06:05

@lilactown why there is a (when ref?

lilactown15:06:14

sometimes the callback passed into the ref prop will be called with a nil value, I’m not totally clear why

tianshu15:06:04

allright thanks

aisamu15:06:17

The docs call that behaviour out: https://reactjs.org/docs/refs-and-the-dom.html#caveats-with-callback-refs (and indeed moving the (fn [ref.. to the outer let/mount-phase solved it for me in the past)

lilactown15:06:44

ah, thank you!