Reagent :component-did-mount
Asked Answered
G

3

18

I'm trying to set the initial focus on an input element

(defn initial-focus-wrapper [element]
  (with-meta element
    {:component-did-mount #(.focus (reagent/dom-node %))}))

(defn chat-input []
  (fn []
    [initial-focus-wrapper
      [:input {:type "text"}]]))

This doesn't work for me though. What am I doing wrong?

Gourami answered 22/12, 2014 at 12:18 Comment(1)
Not a direct answer, but if you provide the autoFocus prop with the value true, that should work.Handmedown
G
14

As sbensu says with-meta only seems to work in reagent on a function. This means it can be used with identity to produce a reusable wrapper as hoped

(def initial-focus-wrapper 
  (with-meta identity
    {:component-did-mount #(.focus (reagent/dom-node %))}))

(defn chat-input []
  (fn []
    [initial-focus-wrapper
      [:input {:type "text"}]]))
Gourami answered 24/12, 2014 at 12:21 Comment(1)
For those struggling you need to use (reagent/as-element [chat-input]) to render it properly.Butcherbird
G
5

I think with-meta should take a function as an argument. From the docs:

(def my-html (atom ""))

(defn plain-component []
  [:p "My html is " @my-html])

(def component-with-callback
  (with-meta plain-component
    {:component-did-mount
     (fn [this]
       (reset! my-html (.-innerHTML (reagent/dom-node this))))}))

So your code should be:

(defn initial-focus-wrapper [element]
  (with-meta element
    {:component-did-mount #(.focus (reagent/dom-node %))}))

(defn chat-input []
  [initial-focus-wrapper
    (fn []
      [:input {:type "text"}]]))
Gwennie answered 23/12, 2014 at 18:35 Comment(1)
You're right. Reagent only seems to work when with-meta is applied to a function. Unfortunately it doesn't seem to work with an anonymous function eitherGourami
O
1

Another way to set the focus on a given component is to use the ":auto-focus true" attribute:

(defn chat-input []
  [:input {:type "text" :auto-focus true}]])
Oxendine answered 29/11, 2019 at 0:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.