Home > Blockchain >  How to add to normal input onChange event that I can use with contentEditable with React
How to add to normal input onChange event that I can use with contentEditable with React

Time:07-18

So I want to have a span <spam contentEditable={true} onChange={...} {...props}>{value}</span>, but I don't have onChange effect on it, rather I need to use onInput, which in the case with React doesn't work, so my question is how can I add onChange event like on input to a span element that has contentEditable on React?

CodePudding user response:

Try onInput method like this, it works!

<div
 contentEditable='true'
 onInput={e => console.log('Text inside div',e.currentTarget.textContent)}
>
 Text inside div
</div>

CodePudding user response:

It works with differnet tags

<div>
  <h1
    contentEditable
    onInput={(event) =>
      console.log('Magic on h1 tag -->', event.currentTarget.textContent)
    }
  >
    Hello StackBlitz!
  </h1>

  <p
    contentEditable
    onInput={(event) =>
      console.log('Magic on p tag -->', event.currentTarget.textContent)
    }
  >
    Start editing to see some magic happen :)
  </p>

  <span
    contentEditable
    onInput={(event) =>
      console.log('Magic on span tag -->', event.currentTarget.textContent)
    }
  >
    Just use `onInput` with `contentEditable`
  </span>
</div>

Try : https://stackblitz.com/edit/react-ts-s5esar?file=App.tsx

  • Related