Getting Started with React
In the last tutorial, we learned that to do React, we needed Node and npm to install some node modules. We did “npm init” to create our package.json and obtained our gulpfile.js. We continue directly from that tutorial to start coding now by creating the usual Hello World type of React component.
1. Start with index.html in the first-react directory …
The article element with the id of “main-content” will be where the Greeting component will be inserted.
Note we reference the main.js script at the bottom of the file. While this file does not exist yet, it will be created by the gulp build process. The filename “main.js” was specified in the gulpfile.js from the last tutorial we saw.
The two require statements says that the code will depend on having the react and the react-dom modules available in the node_modules directory for this app. That was why these two modules was installed in the previous tutorial.
We call the createClass of the React module to create a “class” which we arbitrarily called “Greeting” (class names are uppercase by convention). A class is like analogous to “blueprint” for a house. It is not a house, just the blueprint for it.
To actually have an house, we need to build the house. We say to “instantiate the class”. We instantiate the Greeting class by React’s createElement method which takes the class as the first element and an options object (which we talk about in later tutorial). The object that comes out is the greetingElement. This is the real “house”. It is the object that we can actually use.
To use greetingElement component on our index.html page, we use the ReactDOM module and call its render function passing into it the greetingElement, and the DOM node of on the HTML page (which in our case is #main-content).
3. Next we run gulp from the Node Command Prompt within the first-react directory …
Gulp will transform our app.jsx and produce main.js. If you open main.js, you see that it is over 19,000 lines! That is because gulp saw that our app.jsx depended on react and react-dom modules and included both those modules into the main.js file.
In any case, because our index.html file includes main.js file as a script, it has everything it needs to render the component.
4. Open up index.html in your browser and you will see that it worked…
5. Furthermore, the gulp process has not ended in the console. If you change app.jsx, it will noticed the file change and rebuild main.js. Try it. To end the gulp process, do Ctrl-C in the console.
We learn to variablize the greeting in the next tutorial.