Skip to content

Instantly share code, notes, and snippets.

@rexpan
Last active September 28, 2017 03:29
Show Gist options
  • Select an option

  • Save rexpan/dea0fa17ba04774faa9b0615efa9797f to your computer and use it in GitHub Desktop.

Select an option

Save rexpan/dea0fa17ba04774faa9b0615efa9797f to your computer and use it in GitHub Desktop.
New Features of React 16
const ComponentDomAttributes = () => (<div some-dom-attr={1}></div>); // html => <div some-dom-attr="1"></div>
const ComponentRenderText = ({ title, text }) => `${title}: ${text}.`;
const ComponentRenderFragments = () => ([
<div>A</div>,
<div>B</div>,
]);
class Overlay extends Component {
constructor(props) {
super(props);
this.overlayContainer = document.createElement("div");
document.body.appendChild(this.overlayContainer);
}
componentWillUnmount(){
document.body.removeChild(this.overlayContainer);
}
render() {
return ReactDOM.createPortal(
(<div className="overlay">{this.props.children}</div>),
this.overlayContainer
);
}
}
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
this.setState({ hasError: true });
console.error(error, info);
}
render() {
return (this.state.hasError ? (<div>Something went wrong.</div>) : this.props.children);
}
}
// return null to avoid trigger update
this.setState(state => state.x == newValue ? null : { x: newValue });
// SSR ------------------------------------
// hydrate instead of render in client side
import { render, hydrate } from "react-dom";
render (<App/>, document.getElementById("root")); // rendering the content solely on the client side
hydrate(<App/>, document.getElementById("root")); // rendering on top of server-side rendered markup
// Streaming
import { renderToNodeStream } from "react-dom/server";
const stream = renderToNodeStream(<App/>);
res.write("<!DOCTYPE html><html><head><title>My Page</title></head><body><div id='content'>");
stream.pipe(res, { end: false });
await steamEnd(stream);
res.write("</div></body></html>");
res.end();
function streamEnd(stream) { return new Promise(resolve => stream.on('end', resolve)); }
//----------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment