I'm trying to get an element in my DOM like
<option value>Foo</option>
I found a tutorial online that suggests I could do it as
(reagent.dom/render [:option {:value true} "Foo"] (js/document.getElementById "root"))
But's the true
is getting stringified to "true"
when injected into the DOM
Any ideas?
@clumsyjedi The value attribute on <option> is required to be a string: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option
So <option value>Foo</option>
wouldnโt be valid because itโs not a boolean attribute. You could do [:option {:value ""} "Foo"]
Thanks @josh604. Does this mean reagent is aware of the valid attributes for different html elements? Or react is?
In this case, the HTML itself just doesn't allow any other types than string. (React is/was also aware of some attributes, but not that much anymore: https://reactjs.org/blog/2017/09/08/dom-attributes-in-react-16.html)
Good afternoon ... I'm having a weird situation with a very simple starter project I'm doing to learn reagent
. Here's the entirety of the code:
(ns grader.core
(:require [reagent.dom :as rdom]
[reagent.core :as r]
[clojure.string :as str]))
(defonce gallons (r/atom 0))
(defonce liters (r/atom 0))
(defn gradingResult []
(let [grade (if (= @liters (* @gallons 3.785))
"correct"
"incorrect")]
[:span "Grade " grade]))
(defn grader []
[:div
"Gallons " [:input {:value @gallons :on-change #(reset! gallons (-> % .-target .-value))}] [:br]
"Liters " [:input {:value @liters :on-change #(reset! liters (-> % .-target .-value))}] [:br]
[gradingResult]])
(defn ^:export run []
(rdom/render [grader] (js/document.getElementById "app")))
Maybe worth to say that those functions can be invoked via interop i.e. (js/parseFloat โ23โ)
Sorry, Slack submitted before I got my question in
So, this renders and if I change the first input, gallons
, to a different value, the grade changes between correct & incorrect ... e.g., change 0 -> 1 and it becomes incorrect, change back to 0, it returns to correct
if I do the same with liters
- change 0 -> 1 and it turns incorrect, but reverse it and it just stays incorrect
I'm sure I'm missing something super obvious, but I can't for the life of me figure out what it is
I should be able to put in 1
for gallons and 3.785
for liters and have it reflect correct
, but I cannot.
Input values are strings. You need to coerce them to numbers yourself.
ohhh
:thanks3:
JS does funny things if you use math operations with strings, like "11" * 3.785 is a number again, but the liters value will be string always
yeah, that makes total sense! Thank you so much ๐ Just grabbed cljs.reader/read-string and I'm in business ๐
Better to just use parseInt
or parseFloat
, you (probably) don't want someone inserting Cljs datastructures there, even if read-string doesn't allow eval
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt