Ali Elkhateeb
Ali Elkhateeb

Reputation: 3743

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?

Upvotes: 1

Views: 1376

Answers (2)

vsync
vsync

Reputation: 130491

You cannot assign any React DOM events on children of the react-contenteditable component, because internally it converts all the children to plain HTML string via dangerouslySetInnerHTML React prop:

https://github.com/lovasoa/react-contenteditable/blob/master/src/react-contenteditable.tsx#L53

All React bindings will be lost once the node is rendered

Upvotes: 0

bamse
bamse

Reputation: 4383

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!

Upvotes: 3

Related Questions