Getting started with React — for Beginners

React.Js is a popular Javascript library which is used for building attractive User Interfaces (UI). This post is strictly for beginners who are looking for a good start for learning React Js. To get more detailed information check out the React Js Documentation, which comes handy while developing complex applications.

Akhil Reddy Mallidi
#ByCodeGarage
9 min readJul 8, 2019

--

In this article, I will go through the basic concepts of creating a simple web application by developing an basic React App in which an user can change the background colour of the web application. You can think it as an Dark Mode which is popular now a days. But here we will give four modes for a user. Check the final version of our app below, that we are developing later.

Final Version of the App

Getting Started

React Js is used to create both Single page and Multi page Applications. Using React Js we can develop a complex web application by simple and reusable components. For creating an React app we need a lot of dependencies. Rather than manually installing each of them, we can use React CLI, which is also developed by its developers. So that it creates an react app for us. Installing the create-react-app npm package.

npm install -g create-react-app

g here indicates that we are installing create-react-app package globally.

Let’s start by creating an react app using React CLI.

create-react-app ApplicationName

After executing the above command in Command Line Interface, it downloads and install several dependencies and then it creates an react app. You will get the screen something like this.

Succesful creation of an React App

Now, try running the development server to see the output. First go into the project folder that was created and then execute this following command to start the development server.

# Go to the project foldercd ApplicationName# Start the Development servernpm start

When you are trying to start and development server, you will get something like this.

Basic React App that was created

Open the project folder in any Text Editor. My favorite was Visual Studio Code. You can use Sublime Text, Brackets, Atom etc anyone you are more familiar with. Now while exploring the project directory, we will find the directories like these.

Project Directory

node_modules is something like where we can find all the packages and dependencies were required and installed for our project.

In public folder, we will find the index.html where all our components that were created are added to the index.html file after rendering using index.js in src folder.

In src folder, we will find all the JavaScript files, and also we will create our components there.

In package.json we will find all the dependencies, that were installed. For our basic app we will see react, react-dom, react-scripts installed.

Now we will start editing our App.js. App.js is also a component and is called the root component from where all remaining or children components are rendered accordingly.

Remove all the code in the App.js. We will start typing our own. Components are of two types. Class based Components and Functional Components. We will create our main component in a class based way, since it is a traditional way of creating components in React. I will also show how to create an component in a functional way.

We should plan our components before getting started with coding. In our target app, we have navbar section and body section. So we will be developing our app in two components.

First we should import all the packages needed to create a component. We will import react package. Our App.js component holds only navbar section. Let’s start coding.

// Importing react package
import React, { Component } from 'react';
// Importing App.css file
import './App.css';
class App extends Component {render() {
return(
<div className="App">
<header> <h1 class="App-header"> ReactApp </h1> </header> </div>
)
};
}
# Exporting our componentexport default App;

In the above, our component named App extends the Component package in react. You will see the html code in the component. Actually, it’s not the html code. Its JSX code which will be rendered to html and appended to the index.html by ReactDom.render(), you can see that in index.js file. Unlike in HTML, there will be some differences in JSX code, class in JSX called as className, hence class is only of the predefined word in ES6.

To use our component in other components, we should export our component. That was exactly we have done in the last statement.

Now styling our App.css file, to style our navbar present in the App.js component. You can get best colors for your site in flatui site.

@import url('https://fonts.googleapis.com/cssfamily=Caveat&display=swap');.App {margin: 0 auto;font-family: 'Caveat', cursive;}.App-header {background-color: #282c34;color: aliceblue;margin: 0;padding: 1%;box-shadow: #eee;}

We imported an google font and also added an background color, box-shadow etc to our navbar. Save these two files and open the browser to view all the changes we have done. If you are not able to view, try refreshing the page.

Our App after making changes

Now, I will show how to create an functional based components. We will be using ES6 Arrow function to create an component.

import React from 'react';const person = () => {
return <p> Hii This is functional component </p>
};
export default person;

Now we will be creating our another component. I will name it as ReactComponent. You can give your own name to the component but make sure it is somewhat descriptive about the component, that we are creating.

Create a folder with component name in the src folder. You can give a name of your choice. But we you will not get confused if you are naming with the component name. And create an ComponentName.js and ComponentName.css files in that folder created.

Writing our logic in ReactComponent.js to create our target app. Here also we are creating an component in a class based way.

// Importing the react packageimport React, { Component } from 'react';// Importing the css fileimport './ReactComponent.css';class ReactComponent extends Component {render() {
return(
<div className="body">
<div className="color-list">
<h1> Color Palette </h1> <p> <label> Red </label> <button> Apply </button> </p>
<p>
<label> Blue </label> <button> Apply </button> </p>
<p>
<label> Yellow </label> <button> Apply </button> </p>
<p>
<label> Green </label> <button> Apply </button> </p> </div> <div className="color-alert"> <h1> Mode </h1> <div className="display-mode"> <p> Mode is Applied. </p>
</div>
</div> </div>);}}export default ReactComponent;

The basic idea of our app is to select a color from the available colors and after selecting an particular color, the background should be changed to that color and it should display “X mode is Applied” in the right side of the screen. For that we created a labels and buttons for four colors and display screen to show the color applied.

Also apply the css to our JSX code in the ReactComponent.css file.

.body {    padding: 3%;    font-family: 'Caveat', cursive;    font-size: 20px;    height: 81vh;}.body .color-list {    float: left;    width: 50%;}.body .color-list p label {    width: 30%;    font-size: 175%;    margin: 0 10px 0 0;    display: inline-block;}.body .color-list p button {    font-family: 'Caveat', cursive;    font-size: 125%;    padding: 7px 20px;    margin: 0 0 0 40px;    border: transparent;    background-color: #2d3436;    color: #fff;}.body .color-alert {   float: right;   width: 50%;}.body .color-alert .display-mode {   background-color: rgb(0,0,0, 0.2);   height: 20vh;}.body .color-alert .display-mode p {   font-size: 145%;   padding: 50px 200px;   opacity: 1;}

Call the ReactComponent as <ReactComponent /> in the App.js file to render at a particular position as follows.

// Importing react package
import React, { Component } from 'react';
// Importing App.css file
import './App.css';
class App extends Component {render() {
return(
<div className="App">
<header><h1 class="App-header"> ReactApp </h1></header><ReactComponent /></div>
)
};
}
# Exporting our componentexport default App;

Save these three files and open the browser to view all the changes we have done. If you are not able to view, try refreshing the page.

Our App after making changes

For changing our background color, we should pass the style to the specified element as inline style. So that using state, we can modify the values inside the component. State is a pre-defined word in React, which stores the data as objects of dictionaries, where we can modify them after any particular event inside the component.

Now let’s create a state inside the Component named ReactComponent to apply inline style to the element and to change the color when an button is clicked.

class ReactComponent extends Component {state = {   style : [       { backgroundColor: '#fff' }   ],   viewAlert: [      { colorApplied: 'No'}   ]}}

Here style holds the color of the background color and view alert to display the color. Because we will pass the Hex code, so we wont have color name to display. So we will pass the color name along with Hex code.

To apply Javascript code in the JSX code, we will write all the JS code in { } brackets. Now we will write an JS code to our button, which calls an applyColorHandler() function, which changes the color and displays the color applied.

<button onClick={() => this.applyColorHandler('#e17055', 'Red')}>
Apply
</button>

We are passing Hex code of color, and Color Applied to the applyColorHandler() method.

Writing our applyColorHandler() , which holds our main logic of changing our background color and shows the color applied.

applyColorHandler = (newColor, selColor) => {    //console.log("Clicked");    this.setState({    style : [        { backgroundColor: newColor }
],
viewAlert : [ { colorApplied: selColor} ] })}

We are using setState(), to modify the values that are declared using the state.

Apply the style to the element, where it should be rendered in the ReactComponent.

<div style = {this.state.style[0]} className="body"></div>

Now, the whole ReactComponent looks like as follows

import React, { Component } from 'react';import './ReactComponent.css';class ReactComponent extends Component {state = {    style : [        { backgroundColor: '#fff' }    ],    viewAlert: [        { colorApplied: 'No'}    ]}
applyColorHandler = (newColor, selColor) => { //console.log("Clicked"); this.setState({ style : [ { backgroundColor: newColor } ], viewAlert : [ { colorApplied: selColor} ]})}render() {return (//console.log(this.style),//console.log(this.state.style[0]), <div style = {this.state.style[0]} className="body"> <div className="color-list"> <h1> Color Palette </h1> <p> <label> Red </label> <button onClick={() => this.applyColorHandler('#e17055', 'Red')}> Apply </button> </p>
<p>
<label> Blue </label> <button onClick={() => this.applyColorHandler('#74b9ff', 'Blue')}> Apply </button> </p>
<p>
<label> Yellow </label> <button onClick={() => this.applyColorHandler('#fdcb6e', 'Yellow')}> Apply </button> </p>
<p>
<label> Green </label> <button onClick={() => this.applyColorHandler('#00b894', 'Green')}> Apply </button> </p> </div> <div className="color-alert"> <h1> Mode </h1> <div className="display-mode"> <p> {this.state.viewAlert[0].colorApplied} Mode is Applied. </p> </div> </div></div>);}}export default ReactComponent;

We will use state only in class based components, while in function based components we will use React Hooks to change the values inside the component.

Save all the files and refresh the page. Hurrah ..!! Our target app is now developed and now you got enough strenght about the basics of React. In my further posts, i will take on more core concepts of React.

GitHub link of the Repository- https://github.com/itzzmeakhi/Medium/tree/master/sample-react-app

Let me know if you have anything to ask. Do share the story and clap it if you liked it.

Know more about me- itzzmeakhi.me

--

--

Akhil Reddy Mallidi
#ByCodeGarage

I seek out new knowledge and actively develop new skills. Loves to write. (http://www.itzzmeakhi.dev)