Solution 1 :

Is there anything stopping you from getting the innerText using DOM like this-

var innerText = document.getElementById('elementName').innerText

then passing the value to your reactJS?

Solution 2 :

window.alert only takes a single parameter, so only the first string is shown. If you pass in too many arguments to a javascript function, the extra parameters will simply be ignored. This is different from console.log, which is a variadic function, meaning it will take any number of parameters and display all of them.

Try alert("text: " + inputRef.current.innerText) instead.

Problem :

I have a div that is contenteditable and grabbing the div using useRef(), which is a reactjs hook.

When I try to display the text inside the contenteditable div, the alert shows nothing but the log shows the text.

Is there something I am missing?

this is just a snippet I created

export default function Input() {
  const inputRef = useRef();
  const showText = () => {
    console.log("text: ", inputRef.current.innerText);
    alert("text: ", inputRef.current.innerText);

  return (
      <div ref={inputRef} contentEditable="true" supressContentEditableWarning={true} /> 
      <button onClick={showText}>Show text</button>

It also does’t work when I use it as a value inside an object eg.

const obj = {
  text: inputRef.current.innerText

I will be thankful if someone can help me understand what is going on here!!

just don’t use alert to debug lol.


Comment posted by Pakira

how about if you assign inputRef.current.innerText to a variable and then pass it to both alert and console.log?

Comment posted by Cameron

does innertext return an object or just a string?

Comment posted by

Comment posted by devSwap

@Cameron It returns a string. also, I am importing them as well. I just didn’t put them here. I only included a snippet.

Comment posted by Cameron

I linked a working pen above, does that help? (look at the console)

Comment posted by devSwap

I’ve been told to not go with that route using

Comment posted by MrToenails

DOM is much easier to use, and while it’s a quick fix, it gets the job done with little to no major reprocussions for the jery rigging.

Comment posted by devSwap

hmm, maybe it’s just alert that’s having a hard time displaying it because nonetheless, I should be able to grab the innerText right? I tried your way and I also did

Comment posted by HÃ¥ken Lid

Yes. You should be able to access