Day 1 : React start for Beginner
Tags: react, beginners
Published: 2022-05-15 08:20:58

---
title: Day 1 : React start for Beginner
published: true
description: React start for Beginner
tags: react, beginner
//cover_image: https://direct_url_to_image.jpg
---


Firstly install `npm install create-react-app -g`. So that you will be able to create or run the react application for any folder on you machine. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3srkrtqf91k448gm0hvh.png)

Create react project `create-react-app react-starter` run the command space and provide your application name. So this command creates the react application. And automatically set up the necessary development server babel and web pack. The development server helps us to execute react applications after compilation. 

Webpack package help us to bundle the files. And babel package help us to compile the JavaScript files. From JSX file into regular plain JavaScript files.  

So those compiled JavaScript files can be really execute on the browser. 

After creating the react application you can use either of these commands like npm start, npm run build, npm test, npm run eject. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8yrphwy0anb292q6vd5l.png)

So make sure you're in the correct folder that `react-starter`. And run the command `npm start`

This will automatically compile and execute the react application in the default browser. 

Open the project in any Editor. And in this folder you can see something called public src. 

In the public folder you can see `index.html`. This will be the starting point of your react application. So it contains the typical html syntax. And it imports the icon and contains the basic meta tag. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/glvj71mucqbmnh8c049n.png)

We have tag called div tag with `id=root`. This div tag is the placeholder where the actual react output will be rendered at runtime.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4a4d7fgqf3s5wat28jah.png)

And after that there is nothing much. Just closing of body and html. 

And now coming the **src** folder. You have something called `index.js` which has statement called  `root.render` which eventually invoke **app**. That means it renders the **app component** in the root element which ins already present in the `index.html` file.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7c0ah0k1u05jr1gb8nn6.png)
So where is the definition of the app component? Go to `app.js` file in the **src** folder. There you can see something called App. And is has a **div** tag that renders all the relevant output that we have seen in the browser.    
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sk77lp7ie2s7ee5jsrwa.png)
### Nested Components (App.js)
```
import './App.css';
import React, { Component } from 'react';
import { Button } from 'react-bootstrap'
import NavBar from './NavBar';
import MainContent from './MainContent';

export class App extends Component {
  render(){
    return (
      <div className="App">
        <React.Fragment>
          <NavBar/>
          <MainContent />
        </React.Fragment>
      </div>
    );
  }

}

export default App;
```
### State
State is is the property that contains the content of your component, which you want to render on the page, or it may contain the information that you want to read from the user as well.

Let me add a property called state.
**MainContent.jsx**
```
import { Component } from "react";

export default class MainContent extends Component{
    state = {}
    render(){
        return(
            <div>Main Content</div>
        )
    }
}
```
**state = {}** this is the object literal in JavaScript, which can contain properties and property values can be of any type. Added a property into **state**. 
```
state = {
        appTitle: "Customers"
    }
``` 
How do you render the value of the property from **state**. Open the braces and close the braces. That means your access in the state property of the current working class.
**Example**
```
render(){
        return(
            <div>
                <h3>{this.state.appTitle}</h3>
            </div>
        )
    }
```
Here the **this** keyword represents the current working object of the current class. 
Now title is showing dynamically by using expressions. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3gygpqu26ocyh7ul23sc.png)

### Handle Event
In order to render the same, I just write the **span tag**. So inside this span tag, I would like to render the value of customers control and dynamically by using **react expression**

```
 state = {
        pageTitle: "Customers",
        customerCount: 5
    }
```

```
render(){
        return(
            <div>
                <h3 className="border-bottom m-1 p-1">{this.state.pageTitle} <span className="badge bg-secondary">{this.state.customerCount}</span></h3>
                
            </div>
        )
    }
```
**Output**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qdo9d6u53nc0axh0z0w.png)
So every time when you modify the value of this property automatically, the same gets reflected in this place where the render the particular component property. 

In JavaScript, we have events such as click, double click, focus, blur, key press etc. You can handle almost all types of events by using react. 

You cannot call the methods of another component inside this present component. For example, let me add a button inside the **h4** component

When the user clicks on this particular **refresh** button, I would like to call a method. 

```
import { Component } from "react";

export default class MainContent extends Component{
    state = {
        pageTitle: "Customers",
        customerCount: 5
    }

    render(){
        return(
            <div>
                <h4 className="border-bottom m-1 p-1">{this.state.pageTitle} 
                    <span className="badge bg-secondary m-2">{this.state.customerCount}</span>
                    <button className="btn btn-info" onClick={this.onRefreshClick}>Refresh</button>
                </h4>
            </div>
        )
    }
// executes when the user clicks on Refresh button
    onRefreshClick(){
        console.log("Refresh Click")
    }
}
```
Here I can call any method that is present within the same component. 

So as you can see, when you click on the button, you can see a refresh quickly in the browser console. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9rvl9gozytsshpq7xcnk.png)

### Update Component State
In order to update the state of the page, we have to use **setState** method but should not overwrite the values of the state property directly. Initial state value:
```
 state = {
        pageTitle: "Customers",
        customerCount: 5
    }
```

```
onRefreshClick(){
        console.log("Refresh Click")
        this.setState()
    }
```
In this case, it is a very different matter. It is pre-defined method **setState()**. And you can supply only the property values which want to really update. 

```
onRefreshClick(){
        console.log("Refresh Click")
        this.setState({
            customerCount: 8
        })
    }
```
When click the **Refresh** button, it is showing an error, `saying cannot read property called state of undefined`.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pl45qxij5r2a2omqxhrw.png)
The reason behind it in JavaScript by default, that **this** keyword context will be changed when it is indirectly called. 

Something few change like that **arrow function**.
```
  onRefreshClick = () => {
        console.log("Refresh Click")
        this.setState({
            customerCount: 8
        })
    }
``` 
**Output**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7lmk9yocrw8ped8us7q.png)

### Render list
How do you show this particular array data. 
```
state = {
        pageTitle: "Customers",
        customerCount: 5,
        customers: [
            {id: 1, name: "Bipon Biswas", phone: "123-456"},
            {id: 2, name: "Mead Fahim", phone: "345-456"},
            {id: 3, name: "Mahfuzur Rahman", phone: "986-456"},
            {id: 4, name: "Nayem Ahmed", phone: "432-456"},
            {id: 5, name: "Sajib Biswas", phone: "762-456"},
        ]
    }
```
The map method of JavaScript, every resource and arrow function and execute that arrow function for each element inside the area.

```
<table className="table">
                        <thead>
                            <tr>
                            <th scope="col">#</th>
                            <th scope="col">Customer Name</th>
                            <th scope="col">Phone</th>
                            </tr>
                        </thead>
                        <tbody>
                        {this.state.customers.map((c) => {
                            return(
                                <tr key={c.id}>
                                    <td>{c.id}</td>
                                    <td>{c.name}</td>
                                    <td>{c.phone}</td>
                                </tr>
                            )
                        })}
                        
                        </tbody>
                </table>
```  
**Output**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6v153z7qr7c55c14xw2p.png)
### Conditionally Rendering 

```
{this.state.customers.map((c) => {
                            return(
                                <tr key={c.id}>
                                    <td>{c.id}</td>
                                    <td>{c.name}</td>
                                    <td>{c.phone == null ? "No phone": c.phone}</td>
                                </tr>
                            )
                        })}
```

```
{this.state.customers.map((c) => {
                            return(
                                <tr key={c.id}>
                                    <td>{c.id}</td>
                                    <td>{c.name}</td>
                                    <td>{c.phone == null ? <div className="bg-warning p-2">No phone</div>: c.phone}</td>
                                </tr>
                            )
                        })}
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onok8w7jdu68iy9jvkor.png)
**Another way**
```
{this.state.customers.map((c) => {
                            return(
                                <tr key={c.id}>
                                    <td>{c.id}</td>
                                    <td>{c.name}</td>
                                    <td>{c.phone ? (c.phone) : (<div className="bg-warning p-2 text-center">No phone</div>)}</td>
                                </tr>
                            )
                        })}
```
### Render Method

```
<table className="table">
                        <thead>
                            <tr>
                            <th scope="col">#</th>
                            <th scope="col">Customer Name</th>
                            <th scope="col">Phone</th>
                            </tr>
                        </thead>
                        <tbody>
                        {this.state.customers.map((c) => {
                            return(
                                <tr key={c.id}>
                                    <td>{c.id}</td>
                                    <td>{c.name}</td>
                                    <td>{this.getPhoneToRender(c.phone)}</td>
                                </tr>
                            )
                        })}
                        
                        </tbody>
                </table>
```
```
    getPhoneToRender(phone){
        if(phone){
            return phone
        }
        else{
            return <div className="bg-warning p-2 text-center">No phone</div>
        }
    }
```
### Conditionally Rendering (Functional Component)

```
import { Fragment } from "react";

function ListGroup() {
  let items = ["Dhaka", "Khulna", "Rajshai", "Albania", "Berlin"];
  items = [];


//   if(items.length === 0){
//       return <><h2>List</h2><p>No item found</p></>
//   }

// const message = items.length === 0 ? <p>No Item Found</p>: null;
const getMessage = () => {
    return items.length === 0 ? <p>No Item Found</p>: null;
}

  return (
    <>
      <h2>List</h2>
      {items.length === 0 ? <p>No Item Found</p>: null}
      {/* {message} */}
      {/* {getMessage()} */}
      <ul className="list-group">
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </>
  );
}
export default ListGroup;

```
**Output**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cp13ry82ovgb4c6cwwc6.png)