In this article we will create a simple React.js App – Hello World.
Creating React App
Create a new folder in your computer in location of your choice where you can find it easily.
Example: hello_world_app
Mac Users
1- Open Terminal
2- Change your current directory to the folder we created
Example: cd ~/desktop/hello_world_app
3- Now, run this command –
npx create-react-app .
This command will take some time to setup a React boiler plate app with all the initial setup included.
At the end when successful you will receive a Happy Hacking Message.
At this point our app is ready to run and we can go back to our Code Editor – Visual Studio Code and work on the project.
Also note Visual Studio Code also provides a Terminal interface so its your choice if you would like to use it or Mac’s Terminal.
To keep the tutorial relevant for everyone, I will be using Mac’s Terminal.
4- Lets build the app
Use this command in the Terminal:
npm run build
5- Start the app
npm start
This will start a local server in your computer and you can access the app on your local host.
Now we can access our app in the browser, at start it looks like in the image below.
In further chapters we will be exploring this further and making changes to our hello_world_app
Windows Users
1- Open Command Line
2- Follow Step 2 to 5 from the Mac setup above.
React File Structure
package.json
package.json file contains all the app information like – name, its dependencies and scripts
Our app has 3 dependencies which are –
- react – the library itself
- react-dom – this helps in rendering content to the dom
- react-script – this allows us to define shorthand commands for start and build
index.html
In React, everything is routed through a single file and index.html is that file.
The file contains very simple HTML code, but whats to notice is the <div> element, which has an id assigned to it “root”. This is where React application outputs the main App component, which is basically the primary Javascript file that deals with the rest of components/Javascript files.
So, any component we create like header or footer that will output here
Why this way ?
React is known as single page application library or SPA.
Which basically means, whole application fits on one page.
This comes with many benefits like –
- helps keep data and view in synchronisation
- maintain application state
- fast navigation between application pages
- reduces static resource loading
src folder
index.js
What it does ? here
The file imports –
- react – the main library
- react-dom – this helps in rendering in the browser
and then contains the App component.
ReactDom.render() is the method that allows us to render the App component and specify where to render it.
It takes 2 parameters as follows –
1- <App/> this is what we want to render
2- document.getElementById(root) – helps specify where to render the component
In this case we say render the App component in the root div (which was present in index.html file).