react-jsxrender
react-jsxrender is a drop-in React component designed to render simple, static JSX-like markup at runtime.
Purpose
react-jsxrender is designed to be used with a textarea-like such as CodeMirror, and allow users to produce content containing a mix of regular HTML and custom React components.
Users are given access to a custom environment of React components, but can only set static props, to avoid code injection issues. As long as the exposed components (both HTML elements and React components) are deemed safe, the rendered code will also be safe. Think about it like exposing React components goodness to your users with limited risks. (See, however, the note security at the bottom)
Contrived usage example
Assume you have defined a component class LoremIpsum
which displays dummy text:
/** jsx React.DOM */var React = ;var LoremIpsum = React;moduleexports = LoremIpsum;
Now you want to render a simple markup at runtime such as <div><LoremIpsum /><LoremIpsum /></div>
while forbidding <script>
and <iframe>
tags:
/** jsx React.DOM */var React = ;var JSXRender = ;var env = LoremIpsum: iframe: null script: null;React;
API
A JSXRender
components takes 2 props, env
and code
. env
defines a mapping which augments and/or replaces standard React.DOM
components. To prevent standard DOM elements from being rendered, simply map their lowercased name to null
in env. code
resembles jsx markup, but only constant (non-dynamic) props are accepted, i.e. no {magic}
. Not a single bit of code
will ever be eval
-ed, unless of course some components from env
explicitly eval
s its props.
The rendered markup will be wrapped in a <div class='JSXRender'></div>
. If for any reason code
cannot be rendered, then it will produce instead a <div class='JSXRender JSXRender-error'></div>
containing a description of the error. You may or may not style accordingly.
Note that code
must respect usual jsx conventions, such as using className
instead of class
and htmlFor
instead of for
, special meaning of key
, etc.
Security note
Note that while no {magic}
will occur, usual HTML injection vectors still apply, e.g. you should sanitize code
from things like <a href='javascript:alert("injection!");'>
, maybe blacklist script
, iframe
, etc.