Wednesday, November 26, 2014

Getting Started with React and JSX

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.


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:



  1. JSXTransformer.js - Lets you create JavaScript objects through simple HTML.

  2. react.js - The core React library.


Let's create a file named index.html inside the directory react-<version> and add the following snippet:


[html] < !DOCTYPE html>

[/html]

The above snippet prints Hello, Universe on the UI. You should note the following points:



  1. 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 calling React.createClass(). Every component has a render() method which returns markup to render. In the above snippet we simply returned <p>Hello, Universe</p>, which is then displayed in the view.

  2. 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 our Greeting component into div#greeting-div .

  3. 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.

  4. Since the browser doesn't understand JSX natively, we need to transform it to JavaScript first. This is handled by including the following script:


Continue reading %Getting Started with React and JSX%




by Sandeep Panda via SitePoint

No comments:

Post a Comment