React from a CDN
We’re going to start with the absolute minimum environment for developing React applications.
Setup
Create an index.html
file to use (or use a readymade one) for this exercise and add the following script tags.
<script src='https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js'></script>
Just like most libraries, we can use React from a CDN. Adding this script tag will add React to our project.
Once React is in and you can see that it loads, create a file called app.js
and add it below the React script tag.
<script src='app.js'></script>
Hello, World
Open your app.js
file and add the following code.
var Greeting = React.createClass({
render: function() {
}
});
When writing React, you define components, which you create with the React.createClass
method. Here you’re going to write a simple component which renders a greeting to the screen.
Each component has a render method, which must return either another component, or some HTML. We need is a <h1>
tag with our greeting inside. Add the following code to the render
function.
return (
React.createElement('h1', null, 'Hello, world!')
);
We use the React.createElement
method to describe HTML within our Javascript files. At the moment, all we need to know is that the first argument ('h1'
) is the element or component you want to render and the third argument is the stuff we want to display inside. Don’t worry about the second argument for now.
Once we’ve defined a React component, we actually have to use it somewhere if we want it to show up. Below your greeting component, add the following code.
window.addEventListener('load', function() {
React.render(
React.createElement(Greeting, null),
document.body
);
});
Remember before, that we mentioned that React can render HTML or components? Here is us using a component rather than a tag name. We also have to tell React where to render that component to. In this case, we want it to be rendered directly to the body.
Notice that we wrote Greeting
not 'Greeting'
. There’s a very good reason for this, if you pass a string, then React tries to find corresponding HTML tag. We want to render a component, not a HTML tag. Earlier we declared our component with a variable called Greeting
. All we need to do is pass this variable to React.render
.
Now open index.html
in a browser and you should see a <h1>
tag that says 'Hello, world!'
.
All working? Then it’s time for the next step.