karet
karet copied to clipboard
Respond to React lifecycle methods?
I've been playing around with some of Karet's ideas in a library of my own, but one of the things I'm struggling with is an idiomatic way to respond to componentDidUpdate
with observables.
In my specific example, I want to run a syntax highlighter over a code
element after the element's text has been updated, but because the FromClass
component returned by createElement
never appears in "userland", there's no good way to respond to React's lifecycle methods without dropping down into a "plain" React component, which isn't a terrible solution but something I was hoping to avoid.
Is this something you've run into? How have you solved it?
If I understand correctly, then I actually haven't ran into that specific scenario. I have had cases where I've used non-React components that handle their own rendering given a DOM node, such as the CodeMirror
component in the GitHub snippet recorder example.
So, currently Karet doesn't provide explicit support for the scenario where one wants to perform ad hoc DOM manipulation after each update. You can, of course, do rendering on your own. Something like this (untested draft code):
const Code = ({code}) => {
const element = U.variable()
const updateEffect = U.thru(
U.template({element, code}),
U.consume(({element, code}) => {
element.innerHTML = code.replace(/[\u00A0-\u9999<>&]/gim, i => '&#' + i.charCodeAt(0) + ';')
syntaxHighlight(element)
})
)
return <pre ref={U.refTo(element)} {...{updateEffect}}/>
}
If there is enough need for such a thing, then one possibility would be to e.g. support a special property, say karet-onDidUpdate
, which would allow one to perform updates after rendering. Something like this:
const Code = ({code}) =>
<pre karet-onDidUpdate={element => syntaxHighlight(element)}>
{code}
</pre>
There are probably other plausible APIs for this sort of thing.
However, it is not clear to me whether it makes sense to provide explicit support for this. I suspect that this kind of thing probably only works for very simple cases (such as the above) in the sense that one can't e.g. reliably and portably (as in having the code work with future React versions) render non-trivial DOM using React and then modify that arbitrarily after each update.
FYI, I added a Highlight
component to the GitHub Snippet Recorder example that uses Highlight.js to highlight a code block after changes (just edit the text in the CodeMirror editor on top).