Reacting to React | A Beginner's Guide to React JS 🔥
Tags: react, javascript, webdev, beginners
Published: 2020-08-09 12:15:33



<h3>Hello Amigos 👋!!!</h3>

React or React JS is a JavaScript front-end library from Facebook which lets you create HTML based GUI. It makes the task easier by providing a component-based architecture that was only available to languages like Java and C# before.

Because of this awesome feature, React is quickly becoming the standard JavaScript library for developing front-end. That’s the reason many programmers and developers are learning React or React JS.

<i>But, the big question is how do you learn React? Where should you start? Honestly, I wasted a lot of my time searching for the best material to get started. Watched Tons of youtube videos never completed one, because I was not aware of the fundamental prerequisites of React JS.</i>

In this article, I'm going to take you through the journey of how I started with React JS from just knowing HTML, CSS, and JavaScript(vanilla).

This article is a bit long, but believe me, after completing you'll get started with React JS right away.

Happy Learning ✌!!!


<blockquote><h2>What is React?</h2></blockquote>

React is a front-end library developed by Facebook. It is used for handling the view layer for the web and mobile apps. ReactJS allows us to create reusable UI components. 
Unlike AngularJS, React is not a framework, rather it is an open-source library created by FACEBOOK. 
React allows developers to create/compose large web applications with complex UIs from small and isolated pieces of code called “components” which can change data, without reloading the page.


<blockquote><h2>Pre-requisites :</h2></blockquote>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tzlgwydevsk4l35oiy6b.png)

If you want to work with ReactJS, you need to have a solid knowledge of JavaScript, HTML5, and CSS. Even though ReactJS doesn't use HTML, the JSX is similar so your HTML knowledge will be very helpful.


<blockquote><h2>Why ReactJS?</h2></blockquote>

In traditional web application programming, for even a small change in the webpage, the whole page is reloaded. This makes the web pages slower than they should be.

However, ReactJS solves this problem by only updating what’s necessary.


<blockquote><h2>React Features :</h2></blockquote>
<ul>
<li><b>JSX</b>: JSX is JavaScript syntax extension. JSX is simple JavaScript which allows HTML quoting and uses these HTML tag syntax to render subcomponents. It isn't necessary to use JSX in React development, but but JSX makes React a lot more elegant.</li>
<li><b>Components</b>: React is all about components. You need to think of everything as a component. Components let you split the UI into independent, reusable pieces.</li>
<li><b>Uni-Directional data flow and Flux</b>: React implements one-way data flow which makes it easy to reason about your app. Flux is a pattern that helps keeping your data unidirectional.</li>
</ul>


<blockquote><h2>Advantages of using React : </h2></blockquote>

<ul>
<li>It uses virtual DOM which is a JavaScript object. This will improve apps performance since JavaScript virtual DOM is faster than the regular DOM.</li>
<li>It can be used on the client and server-side as well as with other frameworks.</li>
<li>Components and data patterns improve readability, which helps to maintain larger apps.</li>
</ul>



<blockquote><h2>Create React App : </h2></blockquote>

Before moving further, let’s set up our code. Make sure you have the latest LTS version of Node and npm installed. We’ll use React CLI to help us set up projects easily and run our app using a built-in development server. Create React App comes prefigured with a webpack, along with a plug-in system to run tools like Babel. First, we need to install React CLI. Head over to your terminal then type:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/obeukkg53mdkr1ipffqt.png)

<mark><i>npm install react.cli -g</i></mark> command will install React CLI globally on your system, and <mark><i>create-react-app</i></mark> sets up a new React project. A project named first-app with some files inside it gets created at the required destination. <mark><i>npm start</i></mark> runs the project in a development server on localhost:3000. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7d48weqfd06mgiczcyhe.png)

The React project file structure should look something like: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bnzi4jgwo34tujp9nu4h.png)

All the JavaScript we create will go into the src folder. The React logo on the screen is rendered through App.js where we are outputting the logo.svg. Let’s get rid of these files. Delete <mark>App.css</mark> (this is just a local CSS file for App.js), <mark>App.test.js</mark> (you won’t need it for quite a few days), and logo.svg. Now lets head over to <i><mark>App.js</mark><i> and type the below code into it. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/289ddamt46l4qnemgaoy.png)

Now if you go back to the localhost:3000, you’ll see “Hello, React!”. We have the beginnings of a React app now.

<blockquote><h2>What is JSX and Rendering in React?</h2></blockquote>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hq9vz6u8ycxgz77sh256.png)

<h3>JSX : </h3>
React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, the following are the advantages that come with it:

<ul>
<li>It is faster because it performs optimization while compiling code to JavaScript.</li>
<li>It is also type-safe and most of the errors can be caught during compilation.</li>
<li>It makes it easier and faster to write templates if you are familiar with HTML</li>
</ul>

The following code in App.js renders "Hello, World!!!" on the screen.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gr77sj1y9nnyyygci7py.png)

JavaScript expressions can be used inside JSX. We just need to wrap it with curly brackets {}. The following example will render <em>2</em>.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uk2z5dnn1k804jddzbb7.png)

Know more about JSX at <a href="https://reactjs.org/docs/introducing-jsx.html">JavaScript XML-JSX</a>.

<h3>Rendering in React : </h3>

React element is the smallest renderable unit available in React. We can render such elements using the ReactDOM. React elements are different from DOM elements as React elements are simple javascript objects and are efficient to create. React elements are the building blocks of any React app and should not be confused with React components.

<ul>
<li>Elements are the smallest building blocks of React apps.</li>
<li>An element describes what you want to see on the screen.</li>
</ul>
Let’s say there is a "div" somewhere in your HTML file.
Eg: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ysjxgbmeuyuwkhygp1h8.png)
<ul>
<li>We call this a “root” DOM node because everything inside it will be managed by React DOM.</li>
<li>The following code displays “Hello, React” on the page.</li>
</ul>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/la3b3tygymju0pijzmgg.png)

Know more about Rendering Elements in React at <a href="https://reactjs.org/docs/rendering-elements.html">JavaScript XML-JSX</a>.


<blockquote><h2>Components in React : </h2></blockquote>

<i>React is designed around the concept of reusable components. You define small components and you put them together to form bigger components.</i>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iixh9v0r3jj0f3gy7ncf.jpg)

Every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier. You can see a UI broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final UI.

<ul>
<li>All components small or big are reusable, even across different projects.</li>
<li>The component name starts with a capital letter. This is required since we will be dealing with a mix of HTML elements and React elements. Lowercase names are reserved for HTML elements. In fact, go ahead and try to name the React component just “button” and see how ReactDOM will ignore the function and renders a regular empty HTML button.</li>
<li>Every component receives a list of attributes, just like HTML elements. In React, this list is called props. With a function component, you can name it anything though.</li>
</ul>

Components in React basically return a piece of JSX code which tells what should be rendered on the screen. In React we mainly have two types of components:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/86a8aaekmtzixrln18oz.jpg)

<b>i) Functional Component or Stateless Component:</b>

<ul>
<li>It is simple javascript functions that simply returns html UI </li>
<li>It is also called “stateless” components because they simply accept data and display them in some form that is they are mainly responsible for rendering UI. </li>
<li>It accept properties(props) in function and return html(JSX) </li>
<li>It gives solution without using state </li>
<li>There is no render method used in functional components. </li>
<li>These can be typically defined using arrow functions but can also be created with the regular function keyword. </li>
</ul>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fx5lo38s4yejkd6hcpj4.png)

<b>ii) Class Component or Stateful Component:</b>

<ul>
<li>It is regular ES6 classes that extends component class form react library</li>
<li>Also known as “stateful” components because they implement logic and state.</li>
<li>It must have render() method returning html</li>
<li>It has complex UI Logic</li>
<li>You pass props(properties) to class components and access them with this.props</li>
</ul>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rkabxiq0seyfbbkbwcnv.png)

For now, keep in mind that we will use functional component only when we are sure that our component does not require to interact or work with any other component. That is, these components do not require data from other components however we can compose multiple functional components under a single functional component. We can also use class-based components for this purpose but it is not recommended as using class-based components without need will make your application in-efficient.       

To render a component in React we can initialize an element with a user-defined component and pass this element as the first parameter to ReactDOM.render() or directly pass the component as the first argument to the ReactDOM.render() method.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zcmh8tyua6w6gxjx6grr.png)

Let us see step-wise what is happening in the above example:

<ul>
<li>We call the ReactDOM.render() as the first parameter.</li>
<li>React then calls the component Welcome, which returns <mark>Hello World!</mark> as a result.</li>
<li>Then the ReactDOM efficiently updates the DOM to match with the returned element and renders that element to the DOM element with id as “root”.</li>
</ul>

Know more about components and props at <a href="https://reactjs.org/docs/components-and-props.html">Components in React JS</a>.


<blockquote><h2>props and state in React JS:</h2></blockquote>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vghwx14ekbmlil1vpi0g.png)

<h3>What are props?</h3>

<i>Props are short for properties and they are used to pass data between React components. React’s data flow between components is uni-directional (from parent to child only).</i>

<h3>How do you pass data with props?</h3>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3bbq14y60c5ckn9x7oig.png)

Firstly, we need to define/get some data from the parent component and assign it to a child component’s “prop” attribute.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/old2f6luceulc3o5ufym.png)

“Name” is a defined prop here and contains text data. Then we can pass data with props like we’re giving an argument to a function:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tfj86o9jwypuuo51hnhu.png)

And finally, we use dot notation to access the prop data and render it:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/joctuhtbbgptgui3egaw.png)

<h3>What is state?</h3>

React has another special built-in object called state, which allows components to create and manage their own data. So unlike props, components cannot pass data with state, but they can create and manage it internally.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v5j01dvvflehnnfuowaa.png)

<h3>How do you update a component’s state?</h3>

State should not be modified directly, but it can be modified with a special method called setState( ).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tiamv0d3ovz9ddcromxg.png)

<h3>What happens when state changes?</h3>

A change in the state happens based on user-input, triggering an event, and so on. Also, React components (with state) are rendered based on the data in the state. State holds the initial information.

So when state changes, React gets informed and immediately re-renders the DOM – not the whole DOM, but only the component with the updated state. This is one of the reasons why React is fast.

And how does React get notified? You guessed it: with <mark>setState( )</mark>. The <mark>setState( )</mark> method triggers the re-rendering process for the updated parts. React gets informed, knows which part(s) to change, and does it quickly without re-rendering the whole DOM.

<ul>
<li>State shouldn’t be modified directly – the setState( ) should be used</li>
<li>State affects the performance of your app, and therefore it shouldn’t be used unnecessarily</li>
</ul>

<h3>props vs state</h3>
<ul>
<li>Components receive data from outside with props, whereas they can create and manage their own data with state</li>
<li>Props are used to pass data, whereas state is for managing data</li>
<li>Data from props is read-only, and cannot be modified by a component that is receiving it from outside</li>
<li>State data can be modified by its own component, but is private (cannot be accessed from outside)</li>
<li>Props can only be passed from parent component to child (unidirectional flow)</li>
<li>Modifying state should happen with the <mark>setState( )</mark> method</li>

</ul>

Know more about component state at <a href="https://reactjs.org/docs/faq-state.html">Components state in React JS</a>.

<blockquote><h2>Lifecycle of Components:</h2></blockquote>

React component lifecycle executes in three different intervals/phases. These three phases are Mounting, Updating, and Unmounting. Within these phases, there are methods called Lifecycle hooks that happen in a particular order.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ulbm0bvjka3za3kzbl40.png)

A React Component can go through four stages of its life as follows.

<ul>
<li><b>Initialization</b>: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.</li>
<li><b>Mounting</b>: Mounting is the stage of rendering the JSX returned by the render method itself.</li>
<li><b>Updating</b>: Updating is the stage when the state of a component is updated and the application is repainted.</li>
<li><b>Unmounting</b>: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.</li>
</ul>

<b>Mounting or Initial phase</b>
<ol>
<li>constructor( )</li>
<li>componentWillMount( )</li>
<li>render( )</li>
<li>componentDidMount( )</li>
</ol>

<b>Updating phase</b>
<ol>
<li>componentWillReceiveProps( )</li>
<li>shouldComponentUpdate( )</li>
<li>componentWillUpdate( )</li>
<li>render( )</li>
<li>componentDidUpdate( )</li>
</ol>

<b>Unmounting phase</b>
<ol>
<li>componentWillUnmount( )</li>
</ol>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/48r89wfcxvl34hihqv0e.png)

<h4>Functions of each Phase of Lifecycle<h4>

<b><mark>Initialization</mark>:</b> In this phase, the developer has to define the props and initial state of the component this is generally done in the constructor of the component. The following code snippet describes the initialization process.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/f8nqyi6k6qf6smarwaz5.png)

<b><mark>Mounting</mark>:</b> Mounting is the phase of the component lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time on the webpage. Now React follows a default procedure in the Naming Conventions of this predefined functions where the functions containing “Will” represent before some specific phase and “Did” represent after the completion of that phase. The mounting phase consists of two such predefined functions as described below.
<ul>
<li><b>componentWillMount() Function:</b> As the name clearly suggests, this function is invoked right before the component is mounted on the DOM i.e. this function gets invoked once before the render() function is executed for the first time.</li>
<li><b>componentDidMount() Function:</b> Similarly as the previous one this function is invoked right after the component is mounted on the DOM i.e. this function gets invoked once after the render() function is executed for the first time.</li>
</ul>

<b><mark>Updation</mark></b>: React is a JS library that helps create Active web pages easily. Now active web pages are specific pages that behave according to its user. For example, let’s take the GeeksforGeeks {IDE} webpage, the webpage acts differently with each user. User A might write some code in C in the Light Theme while another User may write a Python code in the Dark Theme all at the same time. This dynamic behavior that partially depends upon the user itself makes the webpage an Active webpage. Now how can this be related to Updation? Updation is the phase where the states and props of a component are updated followed by some user events such as clicking, pressing a key on the keyboard, etc. The following are the descriptions of functions that are invoked at different points of Updation phase.

<ul>
<li><b>componentWillRecieveProps() Function:</b> This is a Props exclusive Function and is independent of States. This function is invoked before a mounted component gets its props reassigned. The function is passed the new set of Props which may or may not be identical to the original Props.</li>
<li><b>setState() Function:</b> This is not particularly a Lifecycle function and can be invoked explicitly at any instant. This function is used to update the State of a component.</li>
<li><b>shouldComponentUpdate() Function:</b> By default, every state or props update re-render the page but this may not always be the desired outcome, sometimes it is desired that on updating the page will not be repainted. The <mark>shouldComponentUpdate()</mark> Function fulfills the requirement by letting React know whether the component’s output will be affected by the update or not. shouldComponentUpdate() is invoked before rendering an already mounted component when new props or state are being received. If returned false then the subsequent steps of rendering will not be carried out. This function can’t be used in case of <mark>forceUpdate()</mark>. The Function takes the new Props and new State as the arguments and returns whether to re-render or not.</li>
<li><b>componentWillUpdate() Function:</b> As the name clearly suggests, this function is invoked before the component is rerendered i.e. this function gets invoked once before the render() function is executed after the updation of State or Props.</li>
<li><b>componentDidUpdate() Function:</b> Similarly this function is invoked after the component is rerendered i.e. this function gets invoked once after the render() function is executed after the updation of State or Props.</li>
</ul>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pu2qx2e8yf8xdu88dm0x.png)

<blockquote><h2>Handling Events in React JS</h2></blockquote>

<i>Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:<i>

<ul>
<li>React events are named using camelCase, rather than lowercase.</li>
<li>With JSX you pass a function as the event handler, rather than a string.</li>
</ul>

For example, the HTML:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1g99fcfp4wthvjxvxr57.png)

is slightly different in React:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wtkzdhjejo57tssqc0kg.png)

Another difference is that you cannot return <mark>false</mark> to prevent default behavior in React. You must call <mark>preventDefault</mark> explicitly. For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/o9cjrnxb2pt8agiukqyw.png)

In React, this could instead be:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bbjca6o0n6y1vqmbo3ss.png)

Here, <mark>e</mark> is a synthetic event. React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility. 

When using React, you generally don’t need to call <mark>addEventListener</mark> to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

Know more about Event Handling in React and passing arguments to it at <a href="https://reactjs.org/docs/handling-events.html">Handling Events-React</a>.



<blockquote><h2>Conditional Rendering in React</h2></blockquote>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tf7mb0je21lvioyvm3d8.jpg)

While developing an application in React or any other JS library/ framework, it is a common use case to show or hide elements based on certain conditions. It can be a simple user interaction — say, we need to show a popup when a user clicks a certain button and hide it when (s)he clicks the cross icon. To quote another example, think authentication — we make a ‘log out’ button visible when (s)he is logged in and make ‘Login/Sign up’ form visible for the opposite situation. This process of executing logic or rendering UI elements basis certain conditions is called conditional rendering.

Conditional rendering in React can be carried out using the following methods:
<ul>
<li>if/else</li>
<li>Ternary operation</li>
<li>Inline IF with Logical && operator</li>
<li>Switch case operator</li>
<li>Higher-Order Components</li>
</ul>

<h3><b>if/else</b></h3>

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if, and let React update the UI to match them. We use an if with our condition and return the element to be rendered.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3bstdnqfz43bktt22ivi.png)

The LoggedStatus component displays either of these components depending on whether a user is logged in or not. A different greeting is rendered depending on the value of isLoggedInprop.

<h3><b>Ternary operation</b></h3>

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.
When condition evaluates to true, the operator returns “This is True”; otherwise (when the condition is false) it returns “This is False”.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/upkciuvnkecel3tt3kt9.png)

<b>Implementation in React JS:</b>

Consider this use case — Show an “Update” button when an edit has been made, else, show the “Edit” button.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zyx1l95xdo9cd9hlpsck.png)

In the above example, when “edited” is true, we’ll show the “Update” button to the user. If “edited” is false, the “Edit” button is rendered.


<h3><b>Inline If with Logical && Operator</b></h3>

&& is a boolean operator, which essentially means “and”. For the condition to evaluate to true, both of the statements must be individually true.
Below is an interesting example. Let’s say we want to render a message saying “You have X tasks to do”. When there are no pending tasks, no message should be displayed.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4o4ockhudeb9e5ccfo4q.png)

Observe carefully — When the length of the array is 3 (which is > 0), we’ll print, “You have 3 Tasks to do.” If the length is 0, we print nothing.


<h3><b>Switch Case operator in React</b></h3>

We can write switch case inline just like normal Javascript for conditional rendering in React. However, you would need a self-invoking JavaScript function. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mzttpvhm6m91evk7n9rz.png)

Note carefully though that you always have to use default for the switch case operator since, in React, a component always needs to return an element or null.

To make it cleaner, we can get the switch out of the render in a function and just call it passing the params we want. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jqm0btw4mprj0ws96uti.png)

The switch case operator helps us to have multiple conditional renderings. 

<h3><b>Higher Order Components</b></h3>

Higher order components or HOCs are often considered a difficult pattern to grasp in ReactJS. HOCs can be used for multiple use cases, however, in this article, we’ll be picking up HOC for conditional rendering.

HOCs are a perfect match for conditional rendering in React and can have several use cases. One of them can be to alter the look of a component. To make it more specific, it can be used to conditionally render the component itself.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/etnrbxlaae8dhyaop58p.png)

In the above example, the List component can focus on rendering the list. It doesn’t have to bother about a loading state. Ultimately, we could add more HOCs to shield away multiple conditional rendering edge cases.

<blockquote><h2>Building and Deploying a React App</h2></blockquote>

Everything we’ve learned so far has been in a development environment. We’ve been compiling, hot-reloading, and updating on the fly. For production, we’re going to want to have static files loading in and none of the source code. We can do this by making a build and deploying it.

Now, if you just want to compile all the React code and place it in the root of a directory somewhere, all you need to do is run the following line:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bu38q4bbeerpfvct8g3v.png)

This will create a build folder that will contain your app. Put the contents of that folder anywhere, and you’re done!

Know more about Building and Deploy at <a href="https://create-react-app.dev/docs/deployment/">React Build and Deployment</a>


<blockquote><h3><i>Thank You for giving this a read!!! Hopefully, this quick overview helps you ease into the world of React and provides you a bit of guidance for your initial journey. Happy Coding!</i></h3> </blockquote>