2 ms·
For me, the best thing about jsx is the fact that it's so easy to create different implementations of `React.createElement` to solve different problems outside
by bluepnume 9y ago
For me, the best thing about jsx is the fact that it's so easy to create different implementations of `React.createElement` to solve different problems outside of the scope of React itself. Want a render function that uses jsx but returns a string, a DOM tree, or something entirely different? Totally possible! I didn't like jsx at first, but the fact that it's so decoupled from React itself counts extremely in its favor, in my view.
For example, for one of my libraries I wanted a really simple way to allow people to include custom templates. I started with string-based templates, but quickly realized that this was inflexible for any kind of event binding or later dom mutations. Achieving that was super easy with jsx -- I just implemented a custom jsx function which directly outputs DOM elements.
Step 1: implement a jsxDom function [^1] which takes (name, props, children) (e.g. https://github.com/krakenjs/xcomponent/blob/master/.babelrc#L11 https://github.com/krakenjs/xcomponent/blob/master/.babelrc#...)
Step 2: point babel to my jsxDom function (e.g. https://github.com/krakenjs/xcomponent/blob/master/src/lib/dom.js#L938-L1015 https://github.com/krakenjs/xcomponent/blob/master/src/lib/d...)
This even allowed some cool hacks like including iframes directly in the jsx, to sandbox sections of the page (since the library is geared towards creating components to be embedded on 3rd party sites):
containerTemplate({ jsxDom }) {
return (
<iframe>
<style>
p {
margin-top: 40px;
}
</style>
<p>I can be sure the styles in this iframe won't affect the parent page</p>
</iframe>
)
}