Skip to content

Instantly share code, notes, and snippets.

@robbintt
Created September 15, 2016 00:44
Show Gist options
  • Save robbintt/eb636cd05e9b56283b0a2061e5a1e531 to your computer and use it in GitHub Desktop.
Save robbintt/eb636cd05e9b56283b0a2061e5a1e531 to your computer and use it in GitHub Desktop.
React example for static sites
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React</title>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-with-addons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.14.0/babel.min.js"></script>
<script type="text/jsx">
/* This script is from plot.ly: http://academy.plot.ly/react/1-introduction/ */
class Counter extends React.Component {
constructor() {
super();
this.state = {
clicks: 0
};
// "`this` is undefined in `increment` because of the way `ES6 Classes` work
// This explanation is terrible. Why again must we bind `this`?
// Trent: According to MDN, bind will make a new `bound function` and bind whatever you pass as `this` for that function. The bound function wraps the original function object.
// Trent: But why is increment set in the constructor? Is increment constructed before the constructor? Maybe... not sure. Alternative idea: Can you bind a function and then define it?
this.increment = this.increment.bind(this);
}
increment() {
this.setState({
clicks: this.state.clicks + 1
});
};
render() {
return (
<div>
<p>This is a Counter component! The button was clicked { this.state.clicks } times.</p>
<Button text="Click me!" onClick={ this.increment } />
</div>
);
}
}
// Button pulls `props` from ReactComponent JSX (React.CreateElement)
var Button = function(props) {
return (
<button onClick={ props.onClick }>{ props.text }</button>
);
}
ReactDOM.render(
<Counter />,
document.getElementById('container')
);
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment