Skip to content

Instantly share code, notes, and snippets.

@mjhea0
Forked from danawoodman/0-react-hello-world.md
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save mjhea0/ca266f402a7a90a2e785 to your computer and use it in GitHub Desktop.

Select an option

Save mjhea0/ca266f402a7a90a2e785 to your computer and use it in GitHub Desktop.

React "Hello World" Examples

Below are a small collection of React examples to get anyone started using React. They progress from simpler to more complex/full featured.

Going Further

Contribute

See things that should be added, improved or clarified? Let me know in the comments!

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>React Hello World</title>
</head>
<body>
<!--
Assuming you install React with Bower, you include React,
then the JSXTransformer which turns JSX into JavaScript
and then your React code.
In production, you'll want to not use the JSXTransformer
and should instead look at using something like Gulp, Grunt or
WebPack to compile JSX into JavaScript. Also, check out:
http://facebook.github.io/react/docs/tooling-integration.html
-->
<script src="bower_components/react/react.js"></script>
<script src="bower_components/react/JSXTransformer.js"></script>
<script src="scripts.jsx" type="text/jsx"></script>
</body>
</html>
// The simplist React component ever:
React.render(<h1>Hello World</h1>, document.body);
// Creating a component
var HelloMessage = React.createClass({
render: function () {
return <h1>Hello {this.props.message}!</h1>;
}
});
React.render(<HelloMessage message="World" />, document.body);
// Managing internal state
var ToggleText = React.createClass({
getInitialState: function () {
return {
showDefault: true
}
},
toggle: function () {
// Invert the chosen default.
// This will trigger an intelligent re-render of the component.
this.setState({ showDefault: !this.state.showDefault })
},
render: function () {
// Default to the default message.
var message = this.props.default;
// If toggled, show the alternate message.
if (!this.state.showDefault) {
message = this.props.alt;
}
return (
<div>
<h1>Hello {message}!</h1>
<a href="" onClick={this.toggle}>Toggle</a>
</div>
);
}
});
React.render(<ToggleText default="World" alt="Mars" />, document.body);
// Combining components together
var ProductItem = React.createClass({
render: function () {
return (
<tr>
<td>{this.props.name}</td>
<td>{this.props.price}</td>
</tr>
);
}
});
var ProductsList = React.createClass({
render: function () {
var products = _.map(this.props.products, function (product, index) {
return (
<ProductItem
key={index}
name={product.name}
price={product.price} />;
);
});
return (
<table>
{products}
</table>
);
}
});
// Could come from an API, LocalStorage, another component, etc...
var products = [
{ name: 'Toast', price: 1499 },
{ name: 'Bacon', price: 3245 },
{ name: 'Coffee', price 300 }
];
React.render(<ProductList products={products} />, document.body);
// Whole Shebang: Component lifecycle, mixins, default props, looping, refs...
// See more here: http://facebook.github.io/react/docs/component-specs.html
// Mixins are just objects with properties that are merged with the compoent
// they are included in.
// See: http://facebook.github.io/react/docs/reusable-components.html#mixins
var MyMixin = {
queryAPIorSomething: function (url, options, successCallback) {
// Do some API magic here...
},
// This does not overwrite the components
// `componentWillUnmount` method but will
// be called along side it.
componetWillUnmount: function () {
// Abor XHR request or something else...
}
};
var WholeShebang = React.createClass({
mixins: [MyMixin],
propTypes: {
// This will log a message on the console if
// items is not defined or if the wrong type
// is supplied.
items: React.PropTypes.array.isRequired
// This will only log if the type is wrong.
prefix: React.PropTypes.string
},
// Sane defaults for your component...
getDefaultProps: function () {
return {
prefix: 'Hello'
}
},
componentWillMount: function () {
// Here you could setState, fetch data from a server or something else...
this.queryAPIorSomething('path/to/api.json', {} , function (data) {
this.setState({ data: data });
}.bind(this));
},
componentDidMount: function () {
// You now have access to the DOM:
console.log(this.getDOMNode().html);
// ... or to component references:
console.log(this.refs.foobar.getDOMNode().html);
},
componentWillUpdate: function () {
console.log('component about to update!');
},
componentDidUpdate: function () {
console.log('component updated!');
// DOM is available here...
},
componentWillUnmount: function () {
// Use this to tear down any event listeners
// or do other cleanup before the compoennt is
// destroyed.
console.log('component will unmount!');
},
shouldComponentUpdate: function () {
// This is called when state/props changed and is
// an opportunity where you can return false if
// you don't want the component to update for
// some reason.
return true;
},
toggle: function () {
// Invert the chosen default.
// This will trigger an intelligent re-render of the component.
this.setState({ showDefault: !this.state.showDefault })
},
render: function () {
var items = _.map(this.props.items, function (item, index) {
// Any time you construct a list of elements or components,
// you need to set the `key` so React can more easily work
// with the DOM.
return <li key={index}>{item}</li>;
});
return (
<div>
<span ref="foobar">Show default: {this.state.showDefault}</span>
<ul>
{items}
</ul>
<a href="" onClick={this.toggle}>Toggle</a>
</div>
);
}
});
React.render(
<WholeShebang items=['Bob', 'Mary', 'Sally'] />,
$('.some-place-in-the-dom').get(0) // Use jQuery to get a place on the page if you want...
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment