0

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?

nevoni3008
  • 227
  • 1
  • 11
  • Does this answer your question? [React.js: onChange event for contentEditable](https://stackoverflow.com/questions/22677931/react-js-onchange-event-for-contenteditable) – Jay Jul 18 '22 at 10:58

2 Answers2

0

Try onInput method like this, it works!

<div
 contentEditable='true'
 onInput={e => console.log('Text inside div',e.currentTarget.textContent)}
>
 Text inside div
</div>
Priyen Mehta
  • 1,096
  • 1
  • 5
  • 19
0

It works with differnet tags

const {
  useState,
  useEffect
} = React;

function App() {
  const [input, setInput] = useState('I am input');
  const [h1, setH1] = useState('I am H1 tag');
  const [p, setP] = useState('I am Paragraph tag');
  const [span, setSpan] = useState('I am Span tag');

  useEffect(() => {
    console.log('Input value change', input);
  }, [input]);

  useEffect(() => {
    console.log('H1 value change', h1);
  }, [h1]);

  useEffect(() => {
    console.log('P value change', h1);
  }, [p]);

  useEffect(() => {
    console.log('Span value change', h1);
  }, [span]);

  return (
  <div>
      <input
        contentEditable
        suppressContentEditableWarning
        value={input}
        onChange={(event) => setInput(event.currentTarget.value)}
      />

      <h1
        contentEditable
        suppressContentEditableWarning
        onBlur={(event) => setH1(event.currentTarget.textContent)}
      >
        {h1}
      </h1>

      <p
        contentEditable
        suppressContentEditableWarning
        onBlur={(event) => setP(event.currentTarget.textContent)}
      >
        {p}
      </p>

      <span
        contentEditable
        suppressContentEditableWarning
        onBlur={(event) => setSpan(event.currentTarget.textContent)}
      >
        {span}
      </span>
      
    </div>
  );
}

ReactDOM.createRoot(
  document.getElementById("root")
).render( <
  App / >
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
Sanchit
  • 460
  • 3
  • 14