Skip to content

Instantly share code, notes, and snippets.

@jacobmischka
Created May 19, 2017 16:04
Show Gist options
  • Save jacobmischka/cb2da353552d7a4d2bf6182ced15f829 to your computer and use it in GitHub Desktop.
Save jacobmischka/cb2da353552d7a4d2bf6182ced15f829 to your computer and use it in GitHub Desktop.
Get from dom
import React, { Component } from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import PropTypes from 'prop-types';
import download from 'downloadjs';
import ActiveEvent from './ActiveEvent.js';
export default class EmailGenerator extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
<button type="button" className="button"
onClick={this.handleClick}>
Click!
</button>
);
}
handleClick() {
const events = this.props.getEvents();
if (events.length > 0) {
const activeEvent = <ActiveEvent event={events[0]} expanded />;
const app = renderToString(activeEvent);
const parser = new DOMParser();
const doc = parser.parseFromString(app, 'text/html');
const dataJsx = doc.querySelector('.active-event').getAttribute('data-jsx');
const styles = document.getElementsByTagName('style');
let activeEventStyles = Array.from(styles)
.filter(style => style.textContent.includes(`data-jsx="${dataJsx}"`))
.map(style => <style dangerouslySetInnerHTML={{__html: style.textContent}}></style>);
const html = '<!DOCTYPE html>' + renderToStaticMarkup(
<html>
<head>{activeEventStyles}</head>
<body>
<div id="root" dangerouslySetInnerHTML={{__html: app}}></div>
</body>
</html>
);
download(html);
}
}
}
EmailGenerator.propTypes = {
getEvents: PropTypes.func.isRequired
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment