Whenever we create a React project and run it with the help of npm start command, it looks like the below image.
Now, we will try to understand how a React application is loaded and started. For this, try to understand these 3 steps:
Step 1
It renders the “index.html” page. In this page, inside the body tag, there is a “div” having id “root”, like this:
- <body>
- <noscript>
- You need to enable JavaScript to run this app.
- </noscript>
- <div id="root"></div>
- </body>
This is the place (div) where a React application gets loaded.
Step 2
Now, this id (root) can be seen in the file “index.js” file inside the render method, like this:
- ReactDOM.render(<App />, document.getElementById('root'));
The render method takes two arguments, first is <App/> component and the second is the place where it renders the code of App component; i.e element (root).
Now, the App component is used inside the render method, but we cannot find any definition or code related to it here. So, where does it come from? It comes from “App.js” file and to use this file in our index.js file we must import it like this:
Step 3
Let’s go to “App.js” file. This is the file where we see our first and only React component present by default in our application. Now, we can remove all the existing lines and put “React App by Mahesh Verma” inside the <p> tag, like,
- class App extends Component {
- render() {
- return (
- <div className="App">
- <header className="App-header">
- <img src={logo} className="App-logo" alt="logo" />
- <h1 className="App-title">Welcome to React</h1>
- </header>
- <p className="App-intro">
- React application by Mahesh Verma.
- </p>
- </div>
- );
- }
- }
We save it and run our application with the help of npm start
Note
We can also change component name from “App” to any other name, but we have to be sure that we also change the same name in App.js file and export the same name.
Conclusion
From the above article, let us just quickly revise how React application gets loaded.
I hope you have learned how a react application gets loaded from this article. For practice purposes, I have attached a sample project called “first-react-app” in which I changed the component name from "App" to "Mahesh" for practice purpose. You can download and modify this as per your requirement. After downloading and extracting the project, first, run "npm install". All your queries related to this article and sample project are always welcomed. Thanks for reading.