React is a framework created by Facebook to make web development easier and more consistent. If you ever wonder how a React website works under the hood, here is a quick examination of the behind-the-scene code that drives this type of application.
An app or website built using React is still governed by the basics of web application in general. Fundamentally, it is still HTML displayed by the browser of your choice. We, obviously, don’t write HTML line by line in a React application as there are plenty built-in tools that generate the HTML codes for us.
If you have tried building a very basic website, you may have encountered the file index.html. That’s usually where you open the file on a browser and it displays whatever HTML codes you put in, usually a few <div> nodes that contains some texts. In the case of a React app, you may be surprised to find out that it also starts with the index.html file. However, the file is only a shell that wraps all the React operations.
Now, let’s take a look at App.js.
App by itself is just a functional component that returns a <div> that contains whatever components the application generates based on user designation. Using the room and furniture analogy above, if the user wants to see the bedroom, the application will generate bedroom furniture and the <App> room will contain the appropriate items for presentation. If user wants to see the kitchen, the application will generate something entirely different and return those fixtures in the <App> room.
In a React app, that room designation is based on path — that address you type on the browser. React provides the BrowserRouter feature that allows you to direct the app to render different components based on the path the user enters. Of course, there can be buttons or links on a webpage that allows the user to get to these components without actually typing in the path on the browser address bar. Take the first item on the list above, for example. If the user types in …/login on the address bar, React will render the Login component as specified. Whatever the Login component contains (usually a box for username and password, and a login button), React will render to the browser.
Once a user logged in, we usually want to display some sort of starting page authorized for the user to see. Since components can be switched based on paths, we can direct the user to a different component from within the application by using “this.props.history.push(‘/xxx’)” method. If we want the user to land in the living room after login, somewhere during the login process we probably gather up the relevant details for the room and then execute “this.props.history.push(‘/livingroom’)”. Now, once the user is authenticated, he/she is in the living room with details appropriate for his/her credentials.
I hope this clears up a bit of the inner working of a React app for those who just started working with it.