Skip to content

Instantly share code, notes, and snippets.

@pveyes
Last active August 23, 2017 15:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pveyes/be1da04bdbf57d6e487daf4b596af7cd to your computer and use it in GitHub Desktop.
Save pveyes/be1da04bdbf57d6e487daf4b596af7cd to your computer and use it in GitHub Desktop.
htmr simple yet powerful custom mapping
import convert from 'htmr';
class Link extends React.Component {
handleClick = e => {
e.preventDefault();
// do something here
alert('It works!');
}
render() {
const { children, ...props } = this.props;
return (
<a onClick={this.handleClick} {...props}>
{children}
</a>
);
}
}
const html = `
<div>
<a href="http://www.google.com">test</a>
</div>
`;
const map = {
a: Link
};
// returns react element
// <div><Link href="http://www.google.com">{'test'}</Link></div>
convert(html, map);
import convert from 'htmr';
import Calendar from './Calendar';
import Clock from './Clock';
const html = `
<div data-type="calendar"></div>
<div data-type="clock"></div>
`;
const DivMapper = props => {
switch (props['data-type']) {
case: 'calendar':
return <Calendar />;
case: 'clock':
return <Clock />;
default:
return <div {...props} />
}
};
const map = {
div: DivMapper
};
// returns an array
// [
// <Calendar />
// <Clock />
// ]
convert(html, map);
import convert from 'htmr';
const html = `
<p>I don't want a paragraph element</p>
`;
const map ={
p: 'div',
};
// returns react element
// <div>I don't want a paragraph element</div>
convert(html, map);
// achieve something like https://github.com/iansinnott/react-string-replace
// for example: to highlight a text
const str = 'what are you doing? You should\'ve not done that!';
const html = str.replace(/(you)/ig, '<strong>$1</strong>');
const map = {
strong: Highlight,
}
// returns an array
// [
// 'what are ',
// <Highlight>you</Highlight>,
// ' doing? ',
// <Highlight>You</Highlight>,
// ' should've not done that!'
// ]
convert(html, map);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment