- Part 1: Installing and Configuring
- Part 2: Understanding Render()
- Part 3: Building Classes
- Part 4: React JSX
Installing and Configuring
There are many ways to get started with React. This series will be concentrating on using React as part of NPM and Node. To that end, there are some assumptions being made:
- Reader is confident with working on the command-line
- Has a recent version of Node.js installed on their system
- Has an editor like Atom installed or is comfortable with working with files from command-line editors.
Open a command-line window and run the following command in an empty directory.
npx create-react-app react-example
After the installation process is done, there will now be a directory called ‘react-example’ created and configured to use React.
Note: The create-react-app runner command recommends that yarn be used. This tutorial series will be using npm and its tools instead.
When the create-react-app runner command is used, it creates default files for using React and setups a demo application. The first action is to delete these files until we need them.
If using a Unix-like system, run the following (making sure that the current directory is ‘src’ inside of ‘react-example’)
rm -f *
If on a Windows system, run the following:
With all of the files removed from the ‘src’ directory, create two new ones: “index.css” and “index.js”
Leave “index.css” empty for now.
Add the following content to the “index.js” file:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') );
In this new file, the first two actions that are happening is that the React and ReactDOM objects are being imported into the file. On the third line, the “index.css” file is being imported.
The last few lines are code are the basis of the new application. The use of ReactDOM.render() function is what kicks off the entire project.
With both “index.css” created and the new content in the file “index.js”, make sure both are saved move back to the projects’s root directory:
Once there, start the application:
After a few seconds, a new tab or window will be opened in the default web browser. It will open to the web server started using the running React code. The results should be “Hello, world!”
While running using npm start, the web server will watch for any changes made to the files in “src” and will refresh the server. During development, this can be very useful to see changes in real-time.
Play around with making some changes to the HTML on line 6 of the code.