Your very first React app …!(Building a react app from scratch)

Yuvraj Agarkar
9 min readJul 7, 2021

--

Hey Guys , Hope ya’ll are doing great , I am back with yet another article ,Today we are gonna Discuss All about Reactjs , What?? is React ,How to use it?? , How does it work and All that jazz , So i want you to fasten your seat belt Load a Cup of Coffee ☕️ And let’s get this going …..

So What is React ?

React is Actually a frontend library developed by Facebook back in 2013 , React makes it easier to divide our whole app (react app or website both mean the same here and are gonna be used interchangeably) into smaller components , Which allows us to use the components multiple times , Improve Code readability , Maintaining becomes easier , makes our app more Efficient , SEO’s and all that goodness .

How does it Work ??

You don’t need to know much about this as it can get pretty overwhelming pretty soon , But in short what React does is , it allows us to use javascript with HTML , which makes it more easier to manage stuff , like You can store a html element in a constant and sende it Or pass it to a function as an argument or return it from the same , ` const greetTag = <h1 className=”greet” >Hello user</h1> `
This is called JSX syntax , Behind the scenes React will compile it and convert it into Javascript Object ,
``` React.createElement(
'h1',
{className: 'greet'},'Hello user'
)
```

So Now you know What is React and How does it work , it’s time to get our hands dirty with this Technology by creating a small Project , We’ll make a Digital Live Clock , Which Looks something like this ..

Nothing too fancy Just a simple Clock ,

Prerequisites
1) You should have nodejs Installed on your machine , It’s pretty easy just download the installer and install it just like any other software
2)You should have a Knowledge about Basics of programming Like what are functions , Classes , Objects ,HTML etc .

Moving on towards our build , First you have to navigate to the directory or folder wherever you wanna create your project and open Your terminal or command prompt window there , Enter Below command
``` npx create-react-app firstapp ```
This command will create a new react app and all the files necessary ,Your project name will be ```firstapp``` You can have any if you want . Hit enter .Process takes some time So Enjoy your Coffee for a while 😉 .

Once done go to the project (```cd firstapp```) and run command ```npm start``` , This will start the server on your local machine and automatically open Chrome for you(keep the server on after you are done with this article just press CTRL + Z to close it) . Technically You are already halfway there , Now you just need to create Your clock Component and render it on the screen , But Before moving Forward take a look at the file structure in your project , There are a lot and for now We will change some of them but don’t get overwhelmed by looking at them Cause.. you can’t give up now we have already come so far.
You don’t need to know much about file structure If you want you can just skip and skim the file structure Section.

The File Structure

File Structure

There are 3 main Folders and a couple of files hanging around Let’s Talk about the first folder node_modules. It contains all the packages and modules required for React to work , You don’t have to mess with that folder as all the 3rd party modules you install in your app also reside there .
Next , we have a public folder , this folder contains all files that are not used when your app is compiled , It also contains our main index.html file , Your app starts from this file we have a special <div> tag inside this file , all our components are rendered inside this <div> tag .Manifest.js contains all information about the author of the app , how should we present it and all that goodness For now we won’t alter that file too.
Next , Comes our src folder which contains all our JS (javascript) files , the App.js is the main components we are gonna render our Clock.js custom inside this App.js component , Other files in this folders having a suffix with test are more useful for app Tester also the file reportWebVitals.js is used by Tester and performance maintenance people. At least for now we don’t need to worry about it .
Index.js real magic happens in this file , What it does is it actually renders our App.js component , And as i said we are gonna render our Clock.js inside App.js component , So i think you guys are getting the leads , We are kinda creating a hierarchy here which goes something like this , Index.js renders our App.js component and App.js Component renders our Clock.js component which we are about to create (App.js is being rendered inside that div with class of root which is present inside index.html).
Talking out other files with .CSS extension They are used for styling out Components

Creating Clock.js

Enough of suspense now let’s create our first Component . Create a new file inside src folder and name it clock.js . Inside clock.js type-out below code .

import React from "react";class Clock extends React.Component {constructor(props) {super(props);this.state = { date: new Date() };}componentDidMount() {this.timerID = setInterval(() => this.tick(), 1000);}componentWillUnmount() {clearInterval(this.timerID);}tick() {this.setState({ date: new Date() });}render() {return (<div><h2>Time is {this.state.date.toLocaleTimeString()}</h2></div>);}}export default Clock;

Stop pulling your hair 👨🏻‍🦲 and let’s try to break this code …..
The first line imports React module , Than we create a class Clock (remeber first letter should be capitalised), Than we have a constructor which accepts props (about props and states in a little bit) than we pass those to super class constructor which is a rule .
Before moving any further Now let’s talk about the LifeCycle shall we ?,
Whenever You render a component few methods are called or triggered automatically , After the constructor call, The render() method is the first to get called , You should return a single HTML tag from this render method. if You have multiple tags embed them into this single one and than return as shown in above Code .
The next 2 methods i wanna talk about are componentDidMount() and componentWillUnmount() , DidMount is called when the component is actually rendered here you can say it is called right after the render() method . This is where you run statements , that requires that the component is already placed in the DOM (in short you can write code that requires the component to be already rendered) .
componentWillUnmount() is called when the component gets destroyed or when we don’t want it anymore , here we can clear some objects and free up space maybe .

Props and States

Props are like Customs attributes of your components , for example you can pass attributes like <Clock name=”MyClock” /> , so if you want to access this name property in any of the method render() or DidMount() you can access it using this.props.name easily
States the name is self explanatory , states are used to handle states of your app , for example whenever you need to change the data of your app or change the time of clock in this case you’ll change the state property of the Component which will force the component to render again (the render() method will run again and we are gonna change the state every second to update the timer)

Total Code breakdown

Ok now we have little background about the stuff , we’ll move forward so in the constructor ` this.state = { date: new Date() }; ` we set the state is equal to new object , this = {key:value} is called a javascript object , here for more, In simple words a JS object is just a set of key and value pairs enclosed inside braces You can have multiple key and Value pairs inside single set of braces separated by a comma (,) {key1:value,key2:value}, Now the state is set …
Moving on we have this line in DidMount() method `this.timerID = setInterval(() => this.tick(), 1000);` , setInterval() is an inbuilt JS function which takes 2 arguments , One a function and the second is the time in milliseconds , in first we are passing a function to a function as an argument , the function we are passing is called an Arrow function, more about Arrow function here . What setInterval does is call the function that we pass every-time after the interval , the interval here is 1s (one second = one thousand milliseconds), we are calling this.tick() every one second, the setInterval returns a timerID , which we use to clear this interval in UnMount() method , this will save up some memory or computations when we no longer need that component , remember when we want to create a class property we create it on the fly in JS , this.propertyName , some properties are already created in super class so make sure not to override those , in this case timerID is a custom property that we created in DidMount() method.

tick() method , just like custom properties tick() method is our own method which we are calling every second , this tick method updates our state() whenever it gets called , here we use ` this.setState({ date: new Date() }); ` to update the state of the app , remember update using setState() ✅ method only never update directly like: this.state={date: new Date()} ❌
Inside setState() we are passing javascript object assigning a new value to our date key , a new Date() object , (Date object keeps track of current date and time ,in JS Date is inbuilt)

render(), this function returns the HTML we want to render on screen ,You see that we access the date key inside the h1 tag there , the date is actually JS part and to use JS inside the HTML we have to embed it into braces{} ,
this.state.date.toLocaleTimeString() , here toLocalTimeString converts the date and time object into string and returns only time and that’s what we need

Exporting , As our component is ready we use export default Clock , on the very last line of our file , this says that we wanna use our component outside the file i.e as discussed earlier we are gonna render this Clock component inside the App.js file . Now we are Almost there ….

Rendering Clock.js

Go to App.js file the very first thing we are gonna do is import out file Clock.js as you import modules the same way

import Clock from "./clock";

Now that we have our exported component imported in this file , we have to just create a tag and place it inside the App function (Don’t change other code in App function just add the Clock tag as demonstrated below)

function App() {return (<div className="App"><header className="App-header"><img src={logo} className="App-logo" alt="logo" /><p>Edit <code>src/App.js</code> and save to reload.<Clock /></p><p> </p><aclassName="App-link"href="https://reactjs.org"target="_blank"rel="noopener noreferrer">Learn React</a></header></div>);}

Create the Clock tag like i have done in above code and that’s it , You should probably have Your entire app ready and working right now , save all your files and your webpage should refresh on its own now .
These things take time to digest and a lot of googling and research but things get better with time , If your code doesn’t work compare it with mine , Here’s link to my project Github ,

That wraps it up guys , Thanks for staying till the end ,I hope this helps , if you have any doubts regarding comment below , Don’t forget to Follow me on Social media where i Post tips related to programming and tech in general , Twitter , Instagram , Medium, Github ,Blogger , Facebook , If this article has helped you Like and Follow me here on meduim as well would really mean a lot , Thanks stay tuned for more See ya …

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yuvraj Agarkar
Yuvraj Agarkar

Written by Yuvraj Agarkar

Aspiring iOS developer , Like to make other developer’s life easy, giving my best to contribute in communities like these

No responses yet

Write a response