React is an open source library for building user interfaces. It lets you create views easily while making sure your UI stays in sync with the underlying data model. This article, targeted towards beginners, covers the basics of React and JSX syntax.
More from this author
Getting Started with React
To get started, head over to the official React official website and download the React starter kit. It contains all the files you need to get started.
Once you have download the .zip
, extract it to a location on your machine. You will see a directory named React-<version>
. On my machine the name of the directory is react-0.12.0
. Open it and go to the build
directory. We are going to need the following two files:
JSXTransformer.js
– Lets you create JavaScript objects through simple HTML.react.js
– The core React library.
Let’s create a file named index.html
inside the directory react-<version>
and add the following snippet:
<!DOCTYPE html>
<html>
<head>
<title>My First React Example</title>
</head>
<body>
<div id="greeting-div"></div>
<script src="build/react.js"></script>
<script src="build/JSXTransformer.js"></script>
<script type="text/jsx">
var Greeting = React.createClass({
render: function() {
return (
<p>Hello, Universe</p>
)
}
});
React.render(
<Greeting/>,
document.getElementById('greeting-div')
);
</script>
</body>
</html>
The above snippet prints Hello, Universe
on the UI. You should note the following points:
- React follows component oriented development. The general idea is to break your whole UI into a set of components. In our case we have just one component named
Greeting
. In React, you create a component by callingReact.createClass()
. Every component has arender()
method which returns markup to render. In the above snippet we simply returned<p>Hello, Universe</p>
, which is then displayed in the view. - A component doesn’t do anything until it’s rendered. To render a component you call
React.render()
with the component to render as the first argument. The second argument is the HTML element where you would like to render your component. In our case we render ourGreeting
component intodiv#greeting-div
. - You might be wondering what
<Greeting/>
really is? This syntax is known as JSX (JavaScript XML) which lets you build DOM nodes with HTML-like syntax. However, JSX is completely optional and you don’t need it in order to use React. But it has a lot of nice features and there is no reason not to take advantage of it. - Since the browser doesn’t understand JSX natively, we need to transform it to JavaScript first. This is handled by including the following script:
<script src="build/JSXTransformer.js"></script>
This script looks for JSX code in <script type="text/jsx"></script>
tags and transforms them into JavaScript on the fly. Transforming JSX in the browser works quite well during development. However, you need to pre-compile your JSX code into JS before deploying into production so that your app renders faster. We will see how to do that later on.
Now you can spin up a server and see the message Hello, Universe
on the UI. Note, if you are on Mac, you can start a server by running the following command from the project’s root directory:
python -m SimpleHTTPServer 8000
Introducing props
React relies on unidirectional data flow. This means that data flow occurs in only one direction i.e. from parent to child via properties. These properties are passed to child components via attributes in JSX. Inside the component you can access the passed properties via the props
object. When the properties change, React makes sure to re-render your component so that your UI is up-to-date with the data model. So, let’s modify the previous snippet to show a random message every two seconds. For the sake of brevity only the script
portion is shown.
<script type="text/jsx">
var Greeting = React.createClass({
render: function() {
return (
<p>{this.props.message}</p>
)
}
});
setInterval(function() {
var messages = ['Hello, World', 'Hello, Planet', 'Hello, Universe']
var randomMessage = messages[Math.floor((Math.random() * 3))]
React.render(
<Greeting message={randomMessage}/>,
document.getElementById('greeting-div')
)
}, 2000);
</script>
The above code chooses a random message from an array and re-renders our component every two seconds. The chosen message is passed as a property called message
. You also need to use pair of curly braces {}
to pass the variable. Now inside the Greeting
component, we access the passed message
via this.props.message
.
If you run the above snippet, it will display a random message every two seconds (assuming a different message is chosen each time).
Just note that the passed props
are immutable types. You just pass various properties to a component via props
. Inside the component you never write to this.props
. This keeps data flow unidirectional and it’s easier to understand how the data change affects the whole application.
Introducing state
and events
In React each component is well encapsulated and maintains its own state (if stateful). A stateful component can store a value in its state and pass it to its child components via props
. This ensures that whenever a component’s state changes, the props
also change. As a result the child components that depend on these props
re-render themselves automatically.
To reinforce this concept let’s modify our previous snippet so that a random message is displayed when a button is clicked. For this we will have two components:
RandomMessage
: This is the parent component which maintains a randomly chosen message in its state.MessageView
: This is a child component which deals with displaying the randomly selected message.
Let’s take a look at each component in detail.
RandomMessage
var RandomMessage = React.createClass({
getInitialState: function() {
return {message: 'Hello, Universe'};
},
_onClick: function() {
var messages = ['Hello, World', 'Hello, Planet', 'Hello, Universe'];
var randomMessage = messages[Math.floor((Math.random() * 3))];
this.setState({message: randomMessage});
},
render: function() {
return (
<div>
<MessageView message={this.state.message}/>
<p><input type="button" onClick={this._onClick} value="Change Message"/></p>
</div>
)
}
});
Our component RandomMessage
maintains a message
in its state. Every React component has a getInitialState()
function which sets the initial state of the component. In our case we initialize our state message
with the value Hello, Universe
.
Next, we need to display a button which, when clicked, updates the state message
with a new value. The following is the markup returned by our component:
<div>
<MessageView message={this.state.message}/>
<p><input type="button" onClick={this._onClick} value="Change Message"/></p>
</div>
As you can see, this component renders another component, MessageView
, and an input button. Do note that the component’s state message
is passed to the child component via a property. Our component also handles click
event on the button by attaching an event listener, this._onClick
. Pay attention to camel case in onClick
. In HTML the event names are written in lowercase i.e. onclick
. But, in JSX you need to use camel case for event names.
Our click
event handler chooses a random message and updates the component’s state by calling:
this.setState({message:randomMessage})
setState()
is a way to inform React about a data change. This method updates the current state of the component and re-renders it. As a result the passed props
are also recomputed and the child components which depend on these props also re-render themselves.
MessageView
var MessageView = React.createClass({
render: function() {
return (
<p>{this.props.message}</p>
)
}
});
This component just displays the passed property message
on the UI. You should note that this is a stateless component and is rendered by the stateful component RandomMessage
.
Now that we have created the required components, it’s time to render the top level component RandomMessage
. This is done as following:
React.render(
<RandomMessage />,
document.getElementById('greeting-div')
);
Thats’s it! Each time you click on the button you will see a different message.
Keeping JSX Separately
Until now we have been writing JSX inside script
tags in HTML. To keep your app structured you should keep each component in its own .jsx
file. So, we can put the above snippet in a file called random-message.jsx
and include it in HTML as shown below:
<script type="text/jsx" src="random-message.jsx"></script>
So, the new HTML markup is:
<!DOCTYPE html>
<html>
<head>
<title>My First React Example</title>
</head>
<body>
<div id="greeting-div"></div>
<script src="build/react.js"></script>
<script src="build/JSXTransformer.js"></script>
<script type="text/jsx" src="src/random-message.jsx"></script>
</body>
</html>
Precompiling JSX
As I mentioned earlier, it’s a good practice to precompile JSX for production usage. To do so you can download a node module called react-tools
using the command npm install react-tools -g
. This tool can continuously watch your JSX files for changes and compile them into JavaScript. This can be done by running the following command:
jsx --watch src/ out/
If you do this you don’t need to include JSXTransformer.js
in your HTML anymore. Rather you should directly include the compiled JavaScript in your markup.
A Note on Virtual DOM
React is very fast because of a technique called virtual DOM. It maintains a fast in-memory representation of the DOM and never directly talks to the real DOM. A component’s render()
function tells React how the DOM should look like at a given time. You have seen me returning React components and HTML elements from components’ render()
function. But that doesn’t produce a real DOM! Rather it’s just a description of the DOM. React computes the diff between this description and the in-memory DOM representation to compute the fastest way to update the browser.
Further Learning
This article provided an overview of React and JSX. Apart from being a rich view technology, React has many other benefits. I wrote an article on my blog highlighting the useful features of React. You can check it out here.
If you want more information on JSX you can check out this official resource. If you want to go ahead and learn something advanced you can read my previous tutorial Creating a Note Taking App with React and Flux.
Thanks for reading. If you have any questions do let me know in comments.
-
Frankie Bagnardi
-
tomraithel
-
adam__roberts
-
-
Saadi Jaan
-
Nick