Skip to content
πŸ” Build DOM elements using JSX automatically
Branch: master
Clone or download
Latest commit ac7c9ee Mar 2, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
media
.editorconfig
.gitattributes
.gitignore
.travis.yml
index.d.ts
index.js Handle boolean attributes correctly (#34) Mar 2, 2019
license
package-lock.json 3.6.0 Mar 2, 2019
package.json 3.6.0 Mar 2, 2019
react.js
readme.md
test.js Handle boolean attributes correctly (#34) Mar 2, 2019

readme.md





Build DOM elements using JSX automatically

Build Status

Install

$ npm install --save dom-chef

Features

  • No API, JSX gets auto transformed into actual DOM elements
  • Protection from XSS injections
  • Partial SVG support
  • React-like props naming (including events)
  • Mix any DOM elements inside

Usage

Make sure to use a JSX transpiler, set JSX pragma to h and optionally the pragmaFrag to DocumentFragment if you need fragment support.

// babel.config.js

const plugins = [
  [
    '@babel/plugin-transform-react-jsx',
    {
      pragma: 'h',
      pragmaFrag: 'DocumentFragment',
    }
  ]
];

// ...
const {h} = require('dom-chef');

const handleClick = e => {
	// <a> was clicked
};

const el = (
	<div class="header">
		<a href="#" class="link" onClick={handleClick}>Download</a>
	</div>
);

document.body.appendChild(el);

Alternative usage

You can avoid configuring your JSX compiler by just letting it default to React and exporting the React object:

const React = require('dom-chef');

This has the advantage of enabling Fragment support with the TypeScript compiler, if you're using it compile JSX without Babel. Related issue: https://github.com/Microsoft/TypeScript/issues/20469

TS17016: JSX fragment is not supported when using --jsxFactory

Recipes

Set classes

const el = <span class="a b c">Text</span>;

// or use `className` alias
const el = <span className="a b c">Text</span>;

Set styles

const el = <div style={{padding: 10, background: '#000'}}/>;

Attach event listeners

const handleClick = e => {
	// <span> was clicked
};

const el = <span onClick={handleClick}>Text</span>;

Mix other elements inside

const title = <h1>Hello World</h1>;
const body = <p>Post body</p>;

const post = (
	<div class="post">
		{title}
		{body}
	</div>
);

Set innerHTML

const dangerousHTML = '<script>alert();</script>';

const wannaCry = <div dangerouslySetInnerHTML={{__html: dangerousHTML}}/>;

Render SVG

Note: Due to the way dom-chef works, tags <a>, <audio>, <canvas>, <iframe>, <script> and <video> aren't supported inside <svg> tag.

const el = (
	<svg width={400} height={400}>
		<text x={100} y={100}>
			Wow
		</text>
	</svg>
);

License

MIT Β© Vadim Demedes

You can’t perform that action at this time.