Search code examples
javascriptreactjscontenteditable

React Contenteditable - how can I assign an onClick to a <span> in react-contenteditable?


Is there anyway I can use something like this:

<span onClick={(e) => console.log(e)}>Testing</span>

Inside react-contenteditable to handle the click on Testing keyword?

When I use the html prop, it would only take an html string, something like <span onclick="something()"></span> I suppose, but is there a way to do it in react instead?

And if I use <span onclick="something()"> where should I define this function something()? I suppose at this point I won't have access to the functions defined in react, right? So how should I do this?


Solution

  • onClick is a React property so react-contenteditable wouldn't know what to do with it - since html expects plain html

    A hacky way to achieve what you want - or pretty close to it - is:

    1. Create an onClickContentEditable function and is it as onClick for ContentEditable
    2. Add an innerRef to ContentEditable
    3. in onClickContentEditable, then the clicked element is ContentEditable do nothing - since we want to interact only with the children of ContentEditable
    4. Based on DOM attributes of the clicked element (tagName, className ...etc) fun with it! :) In onClickContentEditable you can check the DOM attributes of the clicked element and take action accordingly. You could create a class to mark the element you want to click.

    You can test this implementation here - the sandbox is forked from the complex react-contenteditable example. I logged the interactions in the console.

    Hope it helps!