Skip to content

Instantly share code, notes, and snippets.

@pveyes pveyes/eventHandler.js
Last active Aug 23, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.