DEV Community

Cover image for Reacting to React | A Beginner's Guide to React JS šŸ”„
Subhampreet Mohanty šŸ‘Øā€šŸ’» for Spectrum Club

Posted on • Updated on

Reacting to React | A Beginner's Guide to React JS šŸ”„

Hello Amigos šŸ‘‹!!!

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.

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.

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 āœŒ!!!

What is React?

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.

Pre-requisites :

Alt Text

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.

Why ReactJS?

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.

React Features :

  • JSX: 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.
  • Components: React is all about components. You need to think of everything as a component. Components let you split the UI into independent, reusable pieces.
  • Uni-Directional data flow and Flux: 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.

Advantages of using React :

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

Create React App :

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

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

Alt Text

The React project file structure should look something like:

Alt Text

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 App.css (this is just a local CSS file for App.js), App.test.js (you wonā€™t need it for quite a few days), and logo.svg. Now lets head over to App.js and type the below code into it.

Alt Text

Now if you go back to the localhost:3000, youā€™ll see ā€œHello, React!ā€. We have the beginnings of a React app now.

What is JSX and Rendering in React?

Alt Text

JSX :

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:

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

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

Alt Text

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

Alt Text

Know more about JSX at JavaScript XML-JSX.

Rendering in React :

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.

  • Elements are the smallest building blocks of React apps.
  • An element describes what you want to see on the screen.

Letā€™s say there is a "div" somewhere in your HTML file.
Eg:

Alt Text

  • We call this a ā€œrootā€ DOM node because everything inside it will be managed by React DOM.
  • The following code displays ā€œHello, Reactā€ on the page.

Alt Text

Know more about Rendering Elements in React at JavaScript XML-JSX.

Components in React :

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

Alt Text

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.

  • All components small or big are reusable, even across different projects.
  • 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.
  • 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.

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

i) Functional Component or Stateless Component:

  • It is simple javascript functions that simply returns html UI
  • 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.
  • It accept properties(props) in function and return html(JSX)
  • It gives solution without using state
  • There is no render method used in functional components.
  • These can be typically defined using arrow functions but can also be created with the regular function keyword.

Alt Text

ii) Class Component or Stateful Component:

  • It is regular ES6 classes that extends component class form react library
  • Also known as ā€œstatefulā€ components because they implement logic and state.
  • It must have render() method returning html
  • It has complex UI Logic
  • You pass props(properties) to class components and access them with this.props

Alt Text

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

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

  • We call the ReactDOM.render() as the first parameter.
  • React then calls the component Welcome, which returns Hello World! as a result.
  • 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ā€.

Know more about components and props at Components in React JS.

props and state in React JS:

Alt Text

What are props?

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).

How do you pass data with props?

Alt Text

Firstly, we need to define/get some data from the parent component and assign it to a child componentā€™s ā€œpropā€ attribute.

Alt Text

ā€œ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

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

Alt Text

What is state?

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

How do you update a componentā€™s state?

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

Alt Text

What happens when state changes?

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 setState( ). The setState( ) 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.

  • State shouldnā€™t be modified directly ā€“ the setState( ) should be used
  • State affects the performance of your app, and therefore it shouldnā€™t be used unnecessarily

props vs state

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

Know more about component state at Components state in React JS.

Lifecycle of Components:

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

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

  • Initialization: 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.
  • Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.
  • Updating: Updating is the stage when the state of a component is updated and the application is repainted.
  • Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.

Mounting or Initial phase

  1. constructor( )
  2. componentWillMount( )
  3. render( )
  4. componentDidMount( )

Updating phase

  1. componentWillReceiveProps( )
  2. shouldComponentUpdate( )
  3. componentWillUpdate( )
  4. render( )
  5. componentDidUpdate( )

Unmounting phase

  1. componentWillUnmount( )

Alt Text

Functions of each Phase of Lifecycle

Initialization: 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

Mounting: 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.

  • componentWillMount() Function: 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.
  • componentDidMount() Function: 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.

Updation: 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.

  • componentWillRecieveProps() Function: 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.
  • setState() Function: 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.
  • shouldComponentUpdate() Function: 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 shouldComponentUpdate() 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 forceUpdate(). The Function takes the new Props and new State as the arguments and returns whether to re-render or not.
  • componentWillUpdate() Function: 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.
  • componentDidUpdate() Function: 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.

Alt Text

Handling Events in React JS

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

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string.

For example, the HTML:

Alt Text

is slightly different in React:

Alt Text

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

Alt Text

In React, this could instead be:

Alt Text

Here, e 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 addEventListener 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 Handling Events-React.

Conditional Rendering in React

Alt Text

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:

  • if/else
  • Ternary operation
  • Inline IF with Logical && operator
  • Switch case operator
  • Higher-Order Components

if/else

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

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.

Ternary operation

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

Implementation in React JS:

Consider this use case ā€” Show an ā€œUpdateā€ button when an edit has been made, else, show the ā€œEditā€ button.

Alt Text

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.

Inline If with Logical && Operator

&& 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

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.

Switch Case operator in React

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

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

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

Higher Order Components

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

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.

Building and Deploying a React App

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

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 React Build and Deployment

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!

Latest comments (0)