ReactJS 101

Posted on by By Nikhilesh, in Javascript | 0

ReactJS 101

ReactJS is a javascript library by facebook for building state aware UI. Today we’ll be looking at how to get started with it. The following examples are taken from the offical page

Setup

Download react from here and save in folder of your choice. (At the time of writing this, React version was v0.12.2). Now fire up your favourite text editor. Firstly lets make some basic html page.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>React 101</title>
    <!-- change the following paths as per your scripts location -->
    <script src="path/to/build/react.js"></script>
    <script src="path/to/build/JSXTransformer.js"></script>
</head>
<body>
    <div id="example"></div>
</body>
</html>

The JSX Syntax

React uses what the call is JSX which is transformed to vanilla javascript by JSXTransformer.js and it is like writing HTML inside JavaScript. Here’s a simple example.

React.render(<div />, mountNode);

will be compiled to

React.render(React.createElement("div"), mountNode);

Premier component

Add the following code just before the closing body tag and open it in a browser.

<script type="text/jsx">
    var HelloWorld = React.createClass({
        render: function() {
            return <div>Hello {this.props.name}</div>;
        }
    });

    React.render(<HelloWorld name="World!" />, document.getElementById("example"));
</script>

Here’s a jsfiddle

A state aware component

Lets make timer with following code

<script type="text/jsx">
    var Timer = React.createClass({
        getInitialState: function() {
            //Intialize component with state as 0 seconds
            return {secondsElapsed: 0};
        },
        tick: function() {
            //increment the timer and update the state
            this.setState({secondsElapsed: this.state.secondsElapsed + 1});
        },
        componentDidMount: function() {
            //Start the timer when the component is loaded in DOM
            this.interval = setInterval(this.tick, 1000);
        },
        componentWillUnmount: function() {
            //Clear the timer when the component is removed from DOM
            clearInterval(this.interval);
        },
        render: function() {
            return (
                <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
            );
        }
    });

    React.render(<Timer />, document.getElementById("example"));
</script>

Here’s a jsfiddle

Conclusion

This was quick look at react. I’ve just scratched the tip of the iceberg. Head to the documentation and explore for yourselves.

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments