Create a gist now

Instantly share code, notes, and snippets.

Embed
React Hello World Examples

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.

They will hopefully get you over the initial learning curve of the hard parts of React (JSX, props vs. state, lifecycle events, etc).

Usage

You will want to create an index.html file and copy/paste the contents of 1-base.html and then create a scripts.js file and copy/paste the contents of one of the examples into it.

Serving the examples

You will need to serve these examples using HTTP. You cannot just open the HTML files in a web browser. The easiest way to do this on Linux/OSX is the Python web server:

python -m SimpleHTTPServer 8000

As I don't use windows, I can't really help but check out this article on StackOverflow.

Going Further

Contribute

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

Updates

April 24, 2016:

  • Updating to use ReactDOM
  • Fixing various typos (thanks commenters for pointing them out!)
  • Update to use newest React
  • Use Babel instead of JSXTranformer
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>React Hello World</title>
</head>
<body>
<!--
The recommended approach in React is to use a container
dive to load your react code into, rather than using `document.body`.
This can be any element or tag name, just don't use `document.body`
if you can avoid it.
-->
<div id='root'></div>
<!--
For ease of use, we are including the React, ReactDOM and Babel CDN
builds to make getting started as fast as possible.
In production, you'll want to instead look at using something
like Gulp, Grunt or WebPack (my personal recommendation)
to compile JSX into JavaScript. Also, check out:
http://facebook.github.io/react/docs/tooling-integration.html
-->
<script src="https://fb.me/react-15.0.1.js"></script>
<script src="https://fb.me/react-dom-15.0.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<!--
This is where you link to your React code. Can be .js or .jsx
extension, doesn't really matter.
-->
<script src="scripts.js" type="text/babel"></script>
</body>
</html>
/*
The simplist React component ever.
It just renders an H1 tag into the body of the page. Since
JSX is basically just HTML, you can use any valid tag you want.
*/
ReactDOM.render(<h1>Hello World</h1>, document.getElementById('root'));
/*
Creating a component
The most simple component has a `render` method that returns some
JSX. `props` are attributes that are passed into the component
when you instantiate it.
One caveat is that `render` must return a single parent element;
you can't return multiple adjacent JSX tags but must wrap them
in one parent element.
*/
var HelloMessage = React.createClass({
render: function () {
return <h1>Hello {this.props.message}!</h1>;
}
});
ReactDOM.render(<HelloMessage message="World" />, document.getElementById('root'));
/*
Managing internal state
Sets the intial state of the component and then,
when a link is clicked, updates the state.
When the state updates, the component intelligently
and efficiently re-renders.
Note that the `onClick` is the same as the JavaScript
`onClick` event handler. There are many common browser
events that are supported by React. See them all at:
http://facebook.github.io/react/docs/events.html
*/
var ToggleText = React.createClass({
getInitialState: function () {
return {
showDefault: true
}
},
toggle: function (e) {
// Prevent following the link.
e.preventDefault();
// 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>
);
}
});
ReactDOM.render(<ToggleText default="World" alt="Mars" />, document.getElementById('root'));
/*
Combining components together
The most fundamental and useful part of React is that
you can create any number of components and nest them
just like you would any HTML tag. You pass down data
to your components from parent components in a one-way
data flow.
Note: If you use something like Flux/Reflux you have a bit
power when it comes to data storage and event handling.
Using a Flux-like framework with React is very helpful.
*/
var ProductItem = React.createClass({
render: function () {
return (
<tr>
<td>{this.props.name}</td>
<td>{this.props.price}</td>
</tr>
);
}
});
var ProductList = React.createClass({
render: function () {
var products = this.props.products.map(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 }
];
ReactDOM.render(<ProductList products={products} />, document.getElementById('root'));
/*
Whole Shebang
This example shows most of the commonly used React functionality including:
- Component lifecycle events
- Mixins
- Default props
- Prop validation
- Looping
- DOM refs
- Browser events
See more here lifecycle events here:
http://facebook.github.io/react/docs/component-specs.html
This is by no means how you should write React components, it is just meant to illustrate various features of React.
*/
/*
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'
}
},
getInitialState: function () {
return {
showDefault: false,
}
},
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(ReactDOM.findDOMNode(this).innerHTML);
// ... or to component references:
console.log(this.refs.foobar.innerHTML);
},
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 (e) {
// Prevent following the link.
e.preventDefault();
// Invert the chosen default.
// This will trigger an intelligent re-render of the component.
this.setState({ showDefault: !this.state.showDefault })
},
render: function () {
var items = this.props.items.map(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 ? 'True' : 'False'}
</span>
<ul>
{items}
</ul>
<a href="" onClick={this.toggle}>Toggle</a>
</div>
);
}
});
ReactDOM.render(
<WholeShebang items={['Bob', 'Mary', 'Sally']} />,
document.querySelector('.some-tag') // use other selectors, jQuery or something else to find your target on the page if you want
);
@HouCoder

This comment has been minimized.

Show comment
Hide comment
@HouCoder

HouCoder Mar 2, 2015

Very helpful, thank you.

HouCoder commented Mar 2, 2015

Very helpful, thank you.

@danawoodman

This comment has been minimized.

Show comment
Hide comment
@danawoodman

danawoodman Mar 10, 2015

You're very welcome @HouCoder!

Owner

danawoodman commented Mar 10, 2015

You're very welcome @HouCoder!

@thewizster

This comment has been minimized.

Show comment
Hide comment
@thewizster

thewizster Aug 27, 2015

Very clear examples and very helpful. Thanks!

Very clear examples and very helpful. Thanks!

@danawoodman

This comment has been minimized.

Show comment
Hide comment
Owner

danawoodman commented Sep 11, 2015

@thewizster, welcome!

@bramchi

This comment has been minimized.

Show comment
Hide comment
@bramchi

bramchi Oct 31, 2015

Thanks for this great set of examples! #5 wasn't working from the get-go due to some minor typos. Sadly gists don't seem to support pull requests, so you might want to update manually to this working version: https://gist.github.com/bramchi/0260cceeffe027945a0f#file-5-combining-components-js

bramchi commented Oct 31, 2015

Thanks for this great set of examples! #5 wasn't working from the get-go due to some minor typos. Sadly gists don't seem to support pull requests, so you might want to update manually to this working version: https://gist.github.com/bramchi/0260cceeffe027945a0f#file-5-combining-components-js

@irwansyahrir

This comment has been minimized.

Show comment
Hide comment
@irwansyahrir

irwansyahrir Nov 3, 2015

Thanks for a good intro into react.js!

Thanks for a good intro into react.js!

@bigstas

This comment has been minimized.

Show comment
Hide comment
@bigstas

bigstas Nov 12, 2015

Omg, you saved my life. Much better than the other tutorial I was using

bigstas commented Nov 12, 2015

Omg, you saved my life. Much better than the other tutorial I was using

@shinoybabu

This comment has been minimized.

Show comment
Hide comment
@shinoybabu

shinoybabu Jan 15, 2016

Hay danawoodman, It's not working for me.. don't know why...
I can't see scripts.jsx in this folder which you have referred (<script src="scripts.jsx" type="text/jsx"></script>)
Please guide me if I am on a wrong path..

Hay danawoodman, It's not working for me.. don't know why...
I can't see scripts.jsx in this folder which you have referred (<script src="scripts.jsx" type="text/jsx"></script>)
Please guide me if I am on a wrong path..

@brunnock

This comment has been minimized.

Show comment
Hide comment
@brunnock

brunnock Feb 2, 2016

Just got 5-combining-components.js working-

Line 28 uses Underscore.js syntax even though that library is not imported anywhere. I changed it to
var products = this.props.products.map(function (product, index) {

Line 49 is missing a colon.

Line 52 refers to ProductList which isn't defined. I changed it to ProductsList .

brunnock commented Feb 2, 2016

Just got 5-combining-components.js working-

Line 28 uses Underscore.js syntax even though that library is not imported anywhere. I changed it to
var products = this.props.products.map(function (product, index) {

Line 49 is missing a colon.

Line 52 refers to ProductList which isn't defined. I changed it to ProductsList .

@osbornnongqunga

This comment has been minimized.

Show comment
Hide comment
@osbornnongqunga

osbornnongqunga Feb 15, 2016

Thank you for the tutorial...:-)

Thank you for the tutorial...:-)

@che-wf

This comment has been minimized.

Show comment
Hide comment
@che-wf

che-wf Apr 1, 2016

Thank you, @brunnock! I figured out everything else with the exception of the underscore reference and my browser kept throwing and error saying that it wasn't recognized.

Also, Line 33 has an unnecessary semicolon which threw an error for me as well.

che-wf commented Apr 1, 2016

Thank you, @brunnock! I figured out everything else with the exception of the underscore reference and my browser kept throwing and error saying that it wasn't recognized.

Also, Line 33 has an unnecessary semicolon which threw an error for me as well.

@danawoodman

This comment has been minimized.

Show comment
Hide comment
@danawoodman

danawoodman Apr 24, 2016

Hey everyone, thanks for all the kind words and feedback! I wasn't getting Github notifications for these so sorry for not replying earlier! I've added a lot of fixes, upgraded to React 0.15, added ReactDOM and removed dependencies with Lodash so should be a lot more current.

@bramchi @brunnock thanks! I've fixed all the examples so things should be working again :)

@irwansyahrir @bigstas @osbornnongqunga glad this was helpful for you!!

@shinoybabu check out the updated version and see if it works for you now

Owner

danawoodman commented Apr 24, 2016

Hey everyone, thanks for all the kind words and feedback! I wasn't getting Github notifications for these so sorry for not replying earlier! I've added a lot of fixes, upgraded to React 0.15, added ReactDOM and removed dependencies with Lodash so should be a lot more current.

@bramchi @brunnock thanks! I've fixed all the examples so things should be working again :)

@irwansyahrir @bigstas @osbornnongqunga glad this was helpful for you!!

@shinoybabu check out the updated version and see if it works for you now

@danawoodman

This comment has been minimized.

Show comment
Hide comment
@danawoodman

danawoodman Apr 24, 2016

I'm going to start a repo with these examples (and hopefully more!) over here: https://github.com/BuiltByBig/learning-react

If anyone wants to contribute, feel free to submit a PR!

Owner

danawoodman commented Apr 24, 2016

I'm going to start a repo with these examples (and hopefully more!) over here: https://github.com/BuiltByBig/learning-react

If anyone wants to contribute, feel free to submit a PR!

@palerdot

This comment has been minimized.

Show comment
Hide comment
@palerdot

palerdot May 6, 2016

@danwoodman
Excellent React Post. I also would like to point out a very minor typo for the word "Component" in line 92 of "6-whole-shebang.js". One of the simplest, to the point react tutorial in the web. Thanks again for this wonderful tutorial.

palerdot commented May 6, 2016

@danwoodman
Excellent React Post. I also would like to point out a very minor typo for the word "Component" in line 92 of "6-whole-shebang.js". One of the simplest, to the point react tutorial in the web. Thanks again for this wonderful tutorial.

@navneetnagpal

This comment has been minimized.

Show comment
Hide comment
@navneetnagpal

navneetnagpal May 13, 2016

Thank you really helpful :)

Thank you really helpful :)

@jrichardsz

This comment has been minimized.

Show comment
Hide comment
@jrichardsz

jrichardsz May 20, 2016

works like a charm!! Thanks!!

works like a charm!! Thanks!!

@shahidmau

This comment has been minimized.

Show comment
Hide comment
@shahidmau

shahidmau Jul 8, 2016

thanks for good tutorial.. very helpful for, can you please write 2-3 tutorials on data displaying/sending through API?

thanks for good tutorial.. very helpful for, can you please write 2-3 tutorials on data displaying/sending through API?

@mertyesin

This comment has been minimized.

Show comment
Hide comment
@mertyesin

mertyesin Oct 6, 2016

Thanks for sharing this helpful tutorial.

Thanks for sharing this helpful tutorial.

@RobKohr

This comment has been minimized.

Show comment
Hide comment
@RobKohr

RobKohr Oct 23, 2016

5-combining-components.js

line 38~
return ( <table> {products} </table> );

should be
return ( <table> <tbody> {products} </tbody> </table> );

RobKohr commented Oct 23, 2016

5-combining-components.js

line 38~
return ( <table> {products} </table> );

should be
return ( <table> <tbody> {products} </tbody> </table> );

@aamiras-technisys

This comment has been minimized.

Show comment
Hide comment
@aamiras-technisys

aamiras-technisys Nov 14, 2016

Hey man ! First time seeing some React code. Pretty clear your examples ! Thanks !

Hey man ! First time seeing some React code. Pretty clear your examples ! Thanks !

@dgb9

This comment has been minimized.

Show comment
Hide comment
@dgb9

dgb9 Feb 7, 2017

This is the first time I found a project with browser.js that works. Thanks a lot!

dgb9 commented Feb 7, 2017

This is the first time I found a project with browser.js that works. Thanks a lot!

@g522276812

This comment has been minimized.

Show comment
Hide comment
@g522276812

g522276812 Feb 27, 2017

Hi danawoodman,
Thanks for this awesome example, but as you mentioned it won't work without "http".
but it working fine for me in windows as a regular html file +1:

Hi danawoodman,
Thanks for this awesome example, but as you mentioned it won't work without "http".
but it working fine for me in windows as a regular html file +1:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment