Advertisement
  1. Code
  2. JavaScript
  3. React

Getting Started With React and JSX

Scroll to top

In this tutorial, we'll have a look at how to get started with creating a React app and try to understand the basics of JSX. The tutorial assumes that you have a good understanding of HTML and JavaScript.

What Is React?

React is a JavaScript library developed by Facebook to manage the user interface for web applications with ease. One of the main highlights of React is that it helps in creating manageable UI components, which makes it easier to scale large web applications. React works on the concept of Virtual DOM, where it keeps a mirror image of the actual DOM. Whenever a change occurs, React runs a diffing process, identifies the change, and updates it to the actual DOM. The concept of Virtual DOM makes app rendering faster and improves performance.

What Is JSX?

JSX is a JavaScript syntax extension which looks similar to XML. Here is an example:

1
ReactDOM.render(
2
  <h1>Welcome React, TutsPlus !!</h1>,

3
  document.getElementById('container')
4
);

JSX code looks like HTML but is actually a mix of JavaScript and HTML. The above code renders the message inside the h1 tag in the container element. JSX is faster than JavaScript since it performs optimization while compiling the source code. JSX is also preferred since it's easier to use than plain JavaScript code.

From the official docs:

JSX is a XML-like syntax extension to ECMAScript without any defined semantics. It's NOT intended to be implemented by engines or browsers. It's NOT a proposal to incorporate JSX into the ECMAScript spec itself. It's intended to be used by various preprocessors (transpilers) to transform these tokens into standard ECMAScript.

Why Use JSX?

It's is not really required to use JSX while working with React apps. You can go with the plain old JavaScript code. But using JSX has its own advantages:

1. When compared to JavaScript, it's easier to write JSX. It is as simple as opening and closing XML tags. Here is a JSX example:

1
<div>
2
<p>Welcome to TutsPlus</p>
3
</div>

Here is the compiled React code: 

1
"use strict";
2
3
React.createElement(
4
  "div",
5
  null,
6
  React.createElement(
7
    "p",
8
    null,
9
    "Welcome to TutsPlus"
10
  )
11
);

2. JSX code ensures readability and makes maintainability easier.

3. JSX optimizes the code while compiling, so it runs faster compared to the equivalent JavaScript code.

Getting Started

Let's learn further by writing some JSX code and rendering it in the browser. In order to get started with creating a React app, create a simple index.html page with the following page structure:

1
<html>
2
<head>
3
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
4
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
5
	<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
6
7
	<script type="text/babel">
8
	    // JSX code would be here

9
	</script>
10
</head>
11
<body>
12
	<div id="container">
13
14
	</div>
15
</body>
16
</html>

As seen from the above code, we have referenced the react and react-dom scripts in the index.html page. We have also used the babel script reference, which would transform JSX code to react function calls. For example, consider the following JSX code:

1
var grp = <div>
2
  <p>Welcome to TutsPlus</p>

3
</div>;

Babel would transform the above JSX code to the required react function as shown:

1
var grp = React.createElement(
2
  "div",
3
  null,
4
  React.createElement(
5
    "p",
6
    null,
7
    "Welcome to TutsPlus"
8
  )
9
);

Writing React Components Using JSX

Let's create a React component which would display a welcome message. Here is how the code would look:

1
<script type="text/babel">
2
	var Message = React.createClass({
3
		render:function(){
4
			return <h1>Welcome to TutsPlus</h1>

5
		}
6
	});
7
8
	ReactDOM.render(<Message />,document.getElementById('main'));
9
</script>

Message is a react component which returns the above JSX code, which is then compiled to React function code using Babel. Using ReactDOM.render, we render the component inside the HTML element div main

Save the above changes and try browsing the index.html page in the browser, and you should be able to view the message Welcome to TutsPlus in the browser.

Passing Attributes to Components

Most of the time it's required to pass data to our components which would be evaluated or modified and then rendered. Let's have a look at how we can pass attributes to our components and display the data.

Suppose we want to pass a name to our Message component and display the name in our message. First, we'll add a custom attribute to our component.

1
ReactDOM.render(<Message name="Roy" />,document.getElementById('main'));

The passed attribute can be read from inside the component render function using this.props on the component key. Modify the code as shown below:

1
var Message = React.createClass({
2
	render:function(){
3
		return <h1>Welcome to TutsPlus, {this.props.name}</h1>

4
	}
5
});

Save the above changes and browse the index.html page and you should be able to see the message.

1
Welcome to TutsPlus, Roy

Creating a Google Map React Component Using JSX

Now that we are familiar with JSX and creating React components using JSX, let's try creating a React component for displaying Google Maps. 

Start by adding reference to the Google Maps API in the index.html.

1
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

Create a MyMap component as shown below:

1
var MyMap = React.createClass({
2
    render: function() {
3
        return (
4
            <div id="map"><span></span></div>
5
        );
6
    }
7
});
8
9
ReactDOM.render(<MyMap />,document.getElementById('main'));

Add a method called componentDidMount in the React component, and inside that method define the map-related variables as shown:

1
var MyMap = React.createClass({
2
3
    componentDidMount: function() {
4
5
      var latLong = new google.maps.LatLng(-47.888723, 444.675360);
6
7
      var options = {
8
              zoom: 2,
9
              center: latLong
10
          },
11
          map = new google.maps.Map(ReactDOM.findDOMNode(this), options),
12
          marker = new google.maps.Marker({
13
          map:map,
14
          animation: google.maps.Animation.BOUNCE,
15
          position: latLong
16
      });
17
    },
18
19
    render: function() {
20
        return (
21
            <div id="map"><span></span></div>
22
        );
23
    }
24
});

The componentDidMount method is invoked immediately after the initial rendering, and all map objects are initialized inside this method. ReactDOM.findDOMNode finds a reference to the component's DOM node and creates the map object. marker has been defined to set the marker properties like map, position, and animation.

Try rendering the map component inside the #main div.

1
ReactDOM.render(<MyMap />,document.getElementById('main'));

Save the above changes and try browsing the index.html page, and you should be able to view Google Maps in action.

Wrapping It Up

In this tutorial, we saw a basic introduction to React and JSX to get you started. We saw how to create React components using JSX and also created a Google Map React Component. In the coming tutorials, we'll be focusing on some more features of React.

The source code from this tutorial is available on GitHub.

Have you tried creating a React component recently? I would love to hear your experience. Do let me know your thoughts in the comment below.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.