Let’s Act on React from Scratch

Rabab Toor
18 min readJun 17, 2020

After getting hands-on in HTML, CSS, and JavaScript, I wanted to show off my creativity by developing web applications or mobile applications but, things aren’t as easy as they seem. So I decided to document my path of learning. And I think now it’s the best time to act upon ‘React’. 😉

WHAT IS REACT?

It is an open-source JavaScript library for building user interfaces, maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications but remember it only focuses on UI it’s not a framework.

So, without any further delay let’s dive in :)

ARCHITECTURE OF REACT

React has a component based architecture that is you write your code as a component. Components break your application into small encapsulated parts which can later be composed to make more complex user interfaces.

Components also make it possible to write “reusable code”. For instance if you have develop a component for product list on react, the same component can be used for product list in Angular or Vue by simply passing the changed/similar data into that product list component.

React is a declarative paradigm that is you tell React what you want and it will build actual UI from its React DOM library.

Debugging Crash Course

Before start React I want you to learn how to debug errors so, when things go wrong, follow these steps;

  1. Don’t panic! 😅
  2. Manually refresh the page. Sometimes the auto-refreshing mechanism breaks.
  3. Check the browser console, manually refresh the page, and fix any errors you see.
  4. Don’t ignore errors and warnings! Keep the console tidy. If you let problems pileup, non-urgent ones might end up obscuring the one that broke the app. Always scroll to the top and start with the first error; don’t start with the most recent one.
  5. Check the command line terminal where you ran npm start. Look for any errors, and fix those.
  6. If you have no idea what an error means,copy and paste it into Google. Still completely stuck? Stack Overflow has an abundance of React-related questions and answers, and the Reactiflux community is full of friendly people who can help.

LET’S BEGIN WITH YOUR FIRST REACT APP ‘HELLO WORLD’

We’ll start off with a Hello World, of course no self-respecting blog on practical programming would be complete without de rigueur Hello World! application to kick things off.

First, we will create a simple “Hello World” app and then will understand every bit of it.

Environment Setup

Before we dive in, we need to set up an environment. Don’t worry, there’s no boilerplate to clone from GitHub. No Webpack config, either. Instead, we’re using Create React App, a tool by Facebook. It provides a starter project and built-in build tools so you can skip to the fun part — creating your app!

Prerequisites Tools

  1. Node.js (at least 8.10.0).
  2. NPM (ideally version >= 5.2).
  3. Google Chrome, Firefox, or some other modern browser.
  4. Your text editor (I am using VS code) or IDE of choice.

Get Started!

  1. Create a new folder in your system and open VS code in it.
  2. Open new terminal in it and run this command npx create-react-app hello-world.
  3. Soon after command executed, change directory by command cd hello-world and run command npm start.
  4. After few seconds your app will be up and running on localhost:3000.

EXERCISE

Go to App.js file and change code inside <p> tag into “Hello World” save it. and check your browser. Gee, your first app “Hello World” is up and running!

React Application’s Folders and Files Structure

Folders and files structure in React

It is important to understand the file and folder structures in React so, you can control flow when execute your application.

At root level, there are 3 folders and 4 files to begin with:

  1. Package.json is the file that contains dependencies and scripts required for the project.
  2. On the basis of what we use as a package manager; npm or yarn, you will have package-lock.json file or yarn-lock.json file respectively.
  3. Last two files are .gitignore and README.md files.

Now move towards folders, first one is node_modules in which all the node dependencies are installed. It will generate when you execute create-react-app command. Then, there is a public folder it contains three files out of which manifest.json is concerned with web apps. It also contains files related to how the application will display on the client, the most important of those being index.html, which is the HTML template of our page

Third folder is src folder which contains all of the JavaScript, CSS, and image files that will be compiled into a bundle file and injected into index.html.

we’ll be working most in src folder during development.

Starting point for a react application is index.js file. It has root component i.e. ReactDOM.render(<APP/>, document.getElementbyId(‘root’);

index.js

App.js file is responsible for HTML of application and component code will also be placed in it although App.css file is responsible for styling of application and index.css file apply style to body tag in index.html in public folder.

COMPONENTS

Components are basically your application code they are found in app.js file of src folder.

There are two types of components:

Now it’s time for hands-on :) first we will create a functional component.

EXERCISE

  1. Go to App.js file in your hello world app.
  2. Within <div className=”App”> remove all the HTML except <div> tag itself.

3. Now go to src folder, within it create new folder named ‘components’.

4. Within ‘components’ folder, create new file “Greet.js”

5. In Greet.js write import React from “react” (For any component make sure to import it).

6. Now create new function similar as JavaScript function i.e.

Functional Component

As our first functional component has been created but it’s HTML isn’t going to be rendered in browser because the greet component is not yet connected with rest of application.

7. To connnect functional component with rest of the app we have to import this functional component in App.js via import Greet from ‘./components/Greet/’ (you can import any component by following the format ‘./foldername/filename’)

Import Greet component in App.js

8. Final step is to add <Greet/> in <div> element of App.js, save it.

Adding <Greet/> in <div> tag of App.js

Voila! your first functional component is up and running.

You can see it in your browser.

Next let’s create your own class component :)

Class components are basic ES6 classes, these components are similar to functional component in the sense that they receive props (properties) as input and give HTML (JSX) as UI but only difference is that class components can maintain private internal states i.e. it can maintain some information which is private to that component and use that information to describe user interface that is why they are also called stateful components.

Now it’s time for some action! 😎

EXERCISE

  1. In component folder, create another file named Welcome.js
  2. In Welcome.js import React,{Component} from ‘react’ after that write class component and do remember to export it in the end as below:
Class Welcome Component

3. Import this Welcome component at the top of App.js and add <Welcome/> tag in JSX as below:

4. Save it and see results in your browser, ta-da your class component is up and running!

You can reuse any of your component several times by just copy and pasting <component/> tags in <div> element of App.js

PROPS

After learning Functional and Class components it’s time to make these components dynamic but how? here comes props in the scenario :) props (short form of properties) is the optional input that your component except and make it dynamic.

Props can be added to both functional components and class components.

EXERCISE

Get back to App.js and assign name attribute to <Greet/> as in this code snippet:

To access this attribute in Greet.js we have to add parameter to Greet function i.e props as given in code snippet below:

Always use curly braces to add props

Save it and see result in your browser. Expected output will be like this:

Now add second attribute in <Greet/> in App.js and access it in Greet.js as in below code snippet:

To access these props in Greet.js we will add {prop.heroName} in functional component as given below:

Save it and see result in your browser. Expected output will be:

You can also specify other content by add opening and closing tags i.e <Greet><Greet/> as given below:

You can add any tag be it <p>, <button> or <a> in between opening and closing <Greet> tags!

These can be accessed by {props.children} in Greet component as below:

Save it and see result in your browser. Expected output will be:

PROPS WITH CLASS COMPONENT

You can also access props in class component with “this” keyword so, lets do it.

EXERCISE

First go to App.js and add opening and closing <Welcome></Welcome>tags after that add <p>,<button> and <a> tags in between them similarly as in Greet component or you can also try some new tags.

You can add any tag be it <p>, <button> or <a> in between opening and closing <Welcome> tags!

These can be accessed by {this.props.children} in Welcome component as below:

props can be accessed in class via ‘this’ keyword

Remember props are immutable i.e. they cannot be changed!

FRAGMENTS

When we make component we use render method to render something to the screen for single element and its not a problem. But when it comes to render multiple elements we require a “<div>” tag around the content otherwise there will be an error in rendering. This practice is not loved by many developers so, in React 16.2 version, Fragments were introduced and we use them instead of the extraneous <div> tag.

React.Fragment instead of ‘div’ tag

The output of the div tag code and the React.Fragment tag will be same but it is bit faster than previous one as this didn’t require any DOM node, also it takes less memory.

Another shorthand also exists for the above method in which we make use of ‘<>’ and ‘</>’ instead of the ‘React.Fragment’.

STATE

Unlike props, state is changeable and it is maintained inside the components. It plays an important role in any React application.

Let’s create one in which when user click on subscribe button and Welcome Visitor message will change into “Thanks for Subscribing”

EXERCISE

  1. Create a new file Message.js in components folder and create class Message in it.
  2. Initial step of writing state is quit simple, create a constructor () method inside the class component as given in code snippet:

3. Now add button “Subscribe” in render and add event handler onClick ={} with setState() method so when user click on Subscribe message will changed into “Thanks for Subscribing” like in this code snippet:

4. Save it. Gee! your first state is up and running :)

5. Expected output will be like this:

METHODS VS PROPS

We now know that parent component can pass down props to it’s children components and any data in parent component that is passed as props is available in child component.

What if a child component wanted to communicate with the parent component ? Answer is its still props but this time we will pass a reference to a method as props to the child component. Let’s try this,

EXERCISE

  1. Create new file ParentComponent.js in components folder and create a class ParentComponent.
  2. Create a constructor within this component and set a state parentName with the value ‘Parent’
  3. Next define a method greetParent which simply alerts ‘Hello’ with the parentName.
  4. Since we’ll use “this” keyword in greetParent method we have to define “this” in constructor also so, add this.greetParent = this.greetParent.bind(this) in constructor.

5. Create another file ChildComponent.js in components folder

6. Create functional component in it with <button> Greet Parent <button/>

7. In the render method of ParentComponent.js add <ChildComponent/>

8. Import ChildComponent at the top of ParentComponent.js

9. Next in App.js file import ParentComponent at the top and include <ParentComponent/> in the render method. Save it and see your browser. You will see a Greet Parent button but when you click on it nothing will happen.

What we want here is when we click on button in ChildComponent, a method should execute in ParentComponent i.e. a ChildComponent will call ParentComponent method. As we discussed earlier this will be done by props but this time difference is that we pass a method itself as a prop to the ChildComponent.

10. Go back to the ParentComponent.js file and add attribute to the ChildComponent.

PASSING A PARAMETER FROM CHILD COMPONENT TO THE PARENT COMPONENT

Arrow function is the simplest way to pass any parameter from child component to parent component.

Add an arrow function to onClick handler in ChildComponent and pass a parameter for instance a string ‘child’
Now in ParentComponent, pass a parameter in greetHandler i.e. childName and pass it in alert also

Save it and see results in your browser it will be like this:

CONDITIONAL RENDERING

In react conditional rendering works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.

There are Four different approaches for conditional rendering in react i.e.

  1. If/else.
  2. Element variables.
  3. Ternary conditional operator.
  4. Short Circuit Operator.

EXERCISE

If/else

  1. Create a new file named UserGreeting.js in components folder.
  2. Create class UserGreeting with constructor and set this.state isLoggedIn: false.
  3. In render method add if/else condition i.e. if user is logged in it will greet hello user else hello guest.
  4. Don’t forget to export class component and import it on top in App.js.
In App.js add <UserGreeting> component in render method.

5. Save it and as we set isLoggedIn: false, output will be “Welcome Guest” you can change this.state to true so output will be changed into “Welcome Rabab”.

Element variables

As the name suggest in this approach we will use JavaScript variables to store elements.

EXERCISE

  1. First Comment out if/else statement in render method of UserGreeting component. This time set isLoggedIn = true.
  2. Declare a variable inside the render method i.e. let message and below it write condition as in below code snippet;

3. Save it and check your browser this time output will be “Welcome Rabab” because we set isLoggedIn = true.

Ternary conditional operator

This is the simpler approach and benefit of ternary conditional operator is that it can be used inside the JSX.

EXERCISE

  1. First Comment out if/else statement in render method of UserGreeting component. This time set isLoggedIn= false.
  2. Within the render method add return statement and with parenthesis use conditional operator as below;

3. Save it and check your browser. Output will be “Welcome Guest” because we’ve set isLoggedIn = false.

Short Circuit Operator

This is the specific case of ternary operator. In this method we render something or nothing as a condition. In current scenario it will be if isLoggedIn= true it will return “Welcome Rabab” and if isLoggedIn = False it will return nothing!

EXERCISE

  1. First Comment out if/else statement in render method of UserGreeting component. This time set isLoggedIn= True.
  2. Within the render method add return statement and with parenthesis use short circuit method as below;

3. Save it and check your browser. Output will be “Welcome Rabab” because we’ve set isLoggedIn = true. You can change isLoggedIn to false but this time you will get nothing as output.

LIST RENDERING

when we build web applications, a common scenario is to display ‘lists’ for instance list of items, list of courses and so on. So, what we want here is to repeat some HTML for each item in the list.

Beauty of React is that it depends upon JavaScript so, let’s review how you transform lists in JavaScript.

we use the map() function to take an array of numbers and double their values. We assign the new array returned by map()to the variable doubled and log it.

EXERCISE

  1. Create a new file NameList.js in component folder and add functional component in it.
  2. Declare an array of Names list within functional component, I am using my name and my pets names :) and use map method to render <h1> to all the listed names.
  3. Don’t forget to export this NameList in the end of functional component
  4. Import NameList at the top of App.js and add <NameList/> component in the render method.
Code snippet for list rendering

5. Save it and check your browser.

6. With this step we will dive in to learn more, by changing Names array with the array of Personal details. This array has some details about persons (their id, name and skills.) I am using details of my pets :)

change NamesList into PersonsList and use map() method to render JSX as in snippet above

7. In above code snippet personparameter represents object in the list and to access the properties of object we use the dot(.)operator i.e. personparameter.name and personparameter.skill, finally change NamesList to PersonsList. Save it and check your output in browser.

KEYS

In list rendering our output was as expected but when we inspect element we will see dreadful red text with warning in console that a key should be provided for list items.

A key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed.

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys

EXERCISE

Add this key to your PersonsList code and save it. After that check your browser with open console and yay! warning text is no more.

Keys should be given to the elements inside the array to give the elements a stable identity

STYLING AND CSS BASICS

We can style react component by using;

  1. CSS stylesheets
  2. Inline styling
  3. CSS modules

CSS STYLESHEETS

You can write your CSS styling in a separate file, just save the file with the .css file extension, and import it in your application.

EXERCISE

  1. Create a new file Stylesheets.js in the components folder and create a functional Stylesheet component and export it as default.
  2. In return method add JSX <h1>Styling via Stylesheets</h1>
  3. Import this component at top of App.js file also add <Stylesheets/> component in it.
  4. Create a new file named myStyles.css in components folder. Add a class named .primary{color : purple;}
  5. Import myStyles.css at the top of Stylesheets.js file. Add .primary class to <h1> tag like <h1 className={`primary`}> you can use as many classes within backtick.
  6. Save it and wow! your text Styling via Stylesheets is in purple color now.
Code snippet for CSS Stylesheets

INLINE STYLING

You can style an element with the inline style attribute.

EXERCISE

  1. Create a new file Inline.js in the components folder and create a functional Inline component and export it as default.
  2. Before functional component declare a const heading ={fontSize: ‘72px’, color: ‘orange’}
  3. Add style to <h1> i.e. <h1 style={heading}>
  4. Add JSX in return method <h1>Styling via Inline CSS</h1>
  5. Import this component at top of App.js file also add <Inline/> component in it.
  6. Save it and check your browser.
Code snippet for Inline Styling

CSS MODULES

Another way of adding styles to your application is to use CSS Modules. CSS Modules are convenient for components that are placed in separate files.

EXERCISE

  1. Create two style sheets in the source (src) folder named appStyles.css and appStyles.module.css respectively.
  2. In the regular style sheet i.e appStyles.css add a class .error{color: red}. Save it.
  3. In module style sheet i.e appStyles.module.css add a class .success{color: green} and save it.
  4. Import both the files in App.js file.
  5. Now in return method of App.js where previously we used to add component tags add <h1>tag with class name i.e <h1 className={‘error’}>Error</h1>
  6. Now in return method of App.js where previously we used to add component tags add <h1>tag with class name i.e <h1 className={styles.success}>Success</h1>
  7. Save it and check your output in browser.
Code snippet and output of the above exercise

FORMS

In regular HTML form elements like input, text area and so on are responsible for user input and update the respective values but here we want React to control form elements. Such form elements whose value is controlled by React are called controlled components.

The alternative to controlled components, is called uncontrolled components! Uncontrolled components is a method where form data is handled by the DOM itself.

In React, mutable state is typically kept in the state property of components, and only updated with setState().

EXERCISE

  1. Create a new file Form.js in components folder. Create class Form component.
  2. In return method add <form> tags, within this create a <label>Username</label> followed by corresponding <input> tag.
  3. Save it and take a look at the browser, you will see the label and input field until now it is regular HTML
  4. To convert these into controlled component we need two steps to be done.
  5. First step is to create component state to control the value of the element and for this we have to crate a constructor with the setState {username: ‘ ’} and assign this state to the value of input i.e. <input value={this.state.username}. Save it and check your browser you will see same output but with one difference that you can’t add value in the text area. This problem will be solved in second step.
  6. Second step is to add the onChange event with a handler called handleUsernameChange()in input tag i.e. <input onChange={this.state.handleUsernameChange}>
  7. Now define this handler as a class property i.e. arrow function. When we assign onChange handler an event is passed as parameter. Next setState({username: event.target.value})
  8. Save this and check the browser, Gee! now you can add text to your input field. Now you have created Controlled Component.
  9. Task is to create a text area and select tags in the similar way :)
code snippet for controlled component

10. Now its time to submit the form data. Add <button> tag with the value of submit and save it, now you can see submit button in your browser and when you hit the button page refreshes.

11. Now back to VS code and assign onSubmit event to the <form> tag. After that you will need a method for handlSubmit() which will alert a username when button will be clicked. Code snippet is below;

12. Save your code and check your browser for output.

WHERE TO GO FROM HERE

At this point you got basic grip on React’s fundamentals. This is the beginning of your React journey & it’s a right time to Think and React.

--

--