Getting Started with React and JSX

Chris Shatrov JavaScript, React, Technology Snapshot Leave a Comment

I have been with Keyhole Software for nearly four years. Every time I write a new blog post it is about a new framework that I had to pick up and learn that year.

I write a lot of JavaScript daily, but previously never had the chance to start coding a project with React. But this year, I worked on a project with React. So, as expected, I wanted to share my thoughts and my experiences with React.

In this post, I will give a quick introduction to React and talk about its main, most important, components. We will also take a peek at JSX and explain it, and show some code examples, which will help you have a better understanding of this library before you can move on to more complex things.

Quick Introduction

React.js is another extremely popular JavaScript framework. It was developed by Facebook and therefore sees heavy usage on their website. Although, a lot of other web pages use it too. React.js apps are typically written with ES6 instead of ES5 and just like Angular, React applications are all about components.

What makes React usage a piece of cake is its capacity to get adopted with ease and convenience. Because of the short list of lifecycle approaches, it is very easy to understand and use. With the advent of ES2015 and ES2016, a more functional and user-friendly programming has become a cyber norm. Its render function makes it easy for React to comply with a user-friendly and functional programming style.

JSX

Another important feature is JSX. It is React’s special sauce which allows you to embed markup into your JavaScript code. That is what I am focusing on in this post. The separation of HTML from Java is still a hot debate among programmers. The makers of React JS believe that this separation is indeed a very shallow one, as both of them were very well integrated.

Using JSX requires Babel, a transpiler, which takes your JSX code and converts it into plain JavaScript so the browser understands it. As a side benefit of using Babel, we get the ability to use ES6/ES2015 features in our code. There are a number of useful features available as a result, but using them is completely optional.

If you’re just experimenting with React, you can include Babel in your HTML page. This means the JSX code is changed on-the-fly by the browser. This can make page loads slower than otherwise, so it’s not recommended for production applications.

<!DOCTYPE html>
<html>
    <head>
       <script  src=”https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js”></script> 
       <script  src=”https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js”></script>
      <script  src=”https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js”></script>
    </head>
    <body>
         <div  id=”app”></div>
         <script  type=”text/babel”>
              //  Code omitted to keep sample short
         </script>
      </body>
    </html>

We include Babel using the 3rd script. We also included type="text/babel" into the script tag for our code. This is an important step to remember, as otherwise, Babel will not detect that it has to transform the code and you’ll end up with an error.

Now you’re ready to use JSX or ES6 in your code, so let’s take our earlier App component and update it to use JSX.

var  App = React.createClass( {
    render:  function ()  {
        return <div>Something  something  Dark  Side</div>;
    }
} ) ;
 
ReactDOM.render(
    <App  />,
     document.getElementByID(‘app’)
) ;

You can also install React with npm; the best way is to use the Create React App Github repo created by Facebook. This is also the solution that the React Docs recommend.

Apart from React, it also contains Webpack, Babel, Autoprefixer, ESLint, and other developer tools. To get started, use the following commands:

npm install  -g  create-react-app
create-react-app  my-app
cd my-app
npm start

The app can be now accessed on localhost:3000!

JSX Syntax

Now back to JSX. Although it’s not compulsory, you can use the JSX syntax in your React apps. The big advantage of JSX is that it allows you to include HTML in your JavaScript files. This, in turn, makes defining React elements easier.

Now, here are some important things to remember:
1. Tags that start with lowercase (lower camel case) are rendered as regular HTML elements.
2. Tags that start with uppercase (upper camel case) are rendered as React components.
3. Any code written within curly braces {…} are interpreted as literal JavaScript.

See Also:  React NowPlaying Educational Application

Here is how you would define an h1 tag containing a string:

const  element  =  <h1>Hello,  world!</h1>

Even though it might look like it has parts of HTML, it is all JavaScript in reality. What looks like HTML is actually a sugar syntax for defining components and their positioning inside the markup.

You can use a JSX expression and insert different attributes:

const myId = ‘test’
const element = <h1 id={myId}>Hello, world!</h1>

Here’s a JSX snippet that wraps two components into a div tag:

<div>
	<BlogPostList />
	<Sidebar />
</div>

Also, notice that both components are wrapped in one container. React’s render() function can only return a single node. If you want to return two siblings, just add a parent. It can be any tag, not just div.

JSX accepts any kind of JavaScript mixed into it. Whenever you need to add some JS, just put it inside curly braces {}.

For example, here’s how to use a constant value defined elsewhere:

const paragraph = ‘A paragraph’ 
ReactDOM.render(
	<div id=”test”>
		<h1>A title</h1>
		<p>{paragraph}</p>
	</div>,
	document.getElementById(‘myapp’)
)

Components in React

Everything in React is a component and these usually take the form of JavaScript classes. You create a component by extending upon the React-Component class.

class Hello extends React.Component {
	render() {
		return <h1>Hello world!</h1>;
	}
}

As we covered before, every component is going to have a render() method. There you’ll return a description of what you want React to display on the page. In the case above, we simply want it to display an h1 tag with the text ”Hello world!” inside it.

To get our tiny application to render on the screen, we also have to use ReactDOM.render(). This is where we connect our Hello component with the entry point for the app (< div id="root" >< /div >).

ReactDom.render(
	<Hello />
	document.getElementById(“root”)
);

Handling Data

There are two types of data in React: props and state. The difference between the two is tricky to understand in the beginning.

The key difference is that state is private and it can be changed from within the component itself. Props are external and not controlled by the component itself. It’s passed down from components higher up the hierarchy, which also control the data.

A component can change its internal state directly. It can not change its props directly.

Props

A big part of React is reusability, meaning the ability to write a component once and then reuse it in different use cases. For example, using that same component to display different messages.

To achieve this type of reusability, we’ll add props. This is how you pass props to a component:

ReactDOM.render(
	<Hello message=”my friend” />,
	document.getElementById(“root”)
);

This prop is called message and has the value my friend. We can access this prop inside the Hello component by referencing this.props.message, like this:

class Hello extends React.Component {
render() {
	return <h1>Hello {this.props.message}!</h1>;
}
}

Now remember that the reason we’re writing {this.props.message} is because it is needed for escaping.

So now we have a reusable component that can render whatever message we want on the page. However, what if we want the component to be able to change its own data? Then we have to use state instead.

State

The other way of storing data in React is in the component’s state. And unlike props, which can’t be changed directly by the component, the state can.

So if you want the data in your application to change (for example, based on user interactions), it must be stored in a component’s state somewhere in the application.

To initialize the state, simply set this.state in the constructor() method of the class. Our state is an object which, in our case, only has one key called message.

class Hello extends React.Component {
 
	constructor (){
		super();
		this.state = {
			message: “my friend (from state)!”
		};
	}
	
	render() {
		return <h1>Hello {this.state.message}</h1>;
	}
}

Before we set the state, we have to call super() in the constructor. This is because it is uninitialized before super() has been called.

To modify the state, simply call this.setState(), passing in the new state object as the argument. We’ll do this inside a method which we’ll call updateMessage.

class Hello extends React.Component {
	constructor(){
		super();
		this.state = {
			message: “my friend (from state)!”
		};
		this.updateMessage = this.updateMessage.bind(this);
}
 
updateMessage()  {
		this.setState({
			message: “my friend (from changed state)!”
		});
	}
 
	render()  {
		return <h1>Hello {this.state.message}!</h1>;
	}
}

You can easily create a button with an onClick listener that fires the updateMessage method:

<button onClick={this.updateMessage}>Click me!</button>

The updateMessage method then calls this.setState() which changes the this.state.message value.

See Also:  Keyhole Releases Open Source, React-Based Chat UI Component

React Lifecycle Methods

In my opinion, this is very important to understand and is the final topic that I will cover today.

What you see in this picture is the life of a React component from birth (pre-mounting) and death (unmounting). Through lifecycle methods, we can then control what happens when each tiny section of your UI renders, updates, thinks about re-rendering, and then disappears entirely.

componentWillMount
Your component is going to appear on the screen very shortly. That chunky render function, with all its beautifully off-putting JSX, is about to be called. What do you want to do? The answer is… probably not much. The thing about componentWillMount is that there is no component to play with yet, so you can’t do anything involving the DOM.

componentDidMount
Your component is out there, mounted and ready to be used. Now what? In this method you can start AJAX calls to load-in data for your component.

componentWillReceiveProps
Our component was doing just fine when all of a sudden a stream of new props arrive to mess things up. Before our component does anything with the new props, componentWillReceiveProps is called, with the next props as the argument.

shouldComponentUpdate
This method allows us to say: only update if the props you care about change. So basically you can control exactly when your component will re-render.

componentWillUpdate
This method is used instead of componentWillReceiveProps on a component that also has shouldComponentUpdate (but no access to previous props).

componentDidUpdate
This is where updating the DOM in response to prop or state changes takes place.

componentWillUnmount
It’s almost over. Here you can cancel any outgoing network requests, or remove all event listeners associated with the component. So basically, clean up anything that solely involves the component in question . When it’s gone, it should be completely gone.

All in All

Do note that it is important to use the right tool for the job. You may have the best hammer in the world,  but you shouldn’t try to use it to screw something together. Not every project needs or should use React. It’s tempting as a developer to want to implement the shiny new library you’ve learned.

However, React is a high-powered tool. If it is a very simple application, writing it directly in JavaScript can be the correct choice. If your project involves many components with different, often changing states then the project may be a good fit for React. Examples of this include active/inactive navigation items, accordion sections that are expanded/collapsed, dynamic inputs, buttons active/disabled, user login, and access permissions. React helps you manage those changing states and to dynamically present different views to the user based on state information.

Plus, React’s declarative nature of components makes it very easy to get a handle around these complex structures– and keep things in check as the application grows in scale and scope.

Personally, I love coding in React. Having a lot of previous experience in jQuery, Backbone, and Angular, it only took me about two days to feel pretty confident on my own two feet standing in the waters of React.

After reading this post, you now have the basic understanding of React and JSX! Of course, there is a lot more to learn. Hopefully, I helped you get your foot in the door. Now you have a good knowledge base to continue your learning process!


About the Author
Chris Shatrov

Chris Shatrov

Twitter

I am a developer with experience in planning, coding, testing and maintaining web applications. Doing what I love and loving what I do. Professional goal: be the best full stack programmer I can be. "Never settle, always expand and progress."


Share this Post

What Do You Think?