I decided I really needed to start learning React.js. It's the big thing these days, and I don't want to get too far behind, so I'm starting to get on the bandwagon. I still have access to Pluralsight, which has been great so far for other stuff I've been doing, so I'm going through some of their tutorials on there. The first one I'm doing is React.js: Getting Started by Samer Buna. I'm going to just write a few notes as I go along, partly for me to remember better what I'm learning but hopefully to help out others who want to learn React.js as well. Remember, I'm still learning this, so if something's not exactly explained right, give me a little slack. I'll probably come back and fix the blog post. ;)
React.js is a "JavaScript library for building user interfaces". It's used by many as the "V" in MVC. You build the interface using Components, which have two parts: the state and the properties. The state of a component can change as needed; the properties can not. Any time the state is altered, React re-renders that component to the page. The Component outputs HTML to the browser. The Component returns JSX, which is similar to HTML as we know it, but will be converted into pure JavaScript by React. React then looks at the virtual DOM it created and re-renders only the parts that have changed and need re-rendering. This is part of what makes React so fast.
The following is an example of a React component:
var Button = React.createClass({
getInitalState: function () {
return { counter: 0 };
},
clickHandler: function () {
this.setState({ counter: this.state.counter + 1 });
},
render: function () {
return <button onClick={this.clickHandler}>{this.state.counter}</button>;
},
});
This Component is a Button that shows the value of a counter. Each time it is clicked, 1 is added to the counter. the getInitialState function of the component allows you to set counter to use later; we then access counter by using this.state.counter. Remember, it's on the state because it changes.
To get that Component to render to the page, we add the following to our JSX file:
React.render(<Button />, document.getElementById('root'));
The React.render function takes two arguments: the React Component we created (in this case