【React】useRefを用いて値を取得しようとしたらundefinedと言われた。~備忘録~


React HooksのuseRefを用いて、contenteditableにしたdivタグの値を取得するときに躓いたので備忘録として。

import React, { useRef } from 'react'

function InputWithDivTag() {
        const refContainer = useRef('')

        console.log(refContainer.current.value)

        return (
             <div
                  contentEditable="true"
                  ref={refContainer}
                  data-placeholder="入力してください"
             />
        )
}

export default InputWithDivTag

いざ、値を入力してコンソールログの結果を見ると、、、

undefined

何でだろう。
めげません。頑張るのです。

とりあえず、

console.log(refContainer.current.value)

console.log(refContainer.current)

に変更しました。
すると、コンソールログの結果は

<div contenteditable="true" data-placeholder="入力してください">a</div>

refContainerが空っぽなわけではなさそうです。
考えます。
そもそも、参考にしたコードではcurrent.valueはinputタグに使われていた。
同じ入力でも、contenteditableによって入力可能となったdivタグとinputタグでは何かが違うのでは。
ググろう。
let me google it!

console.log(refContainer.current.innerText)

これで思ったように値を取得できました。
valueではなくinnerTextを使えば良かったのですね。