Beginner's guide to creating a React app
Tags: react, beginners, webdev
Published: 2020-06-29 02:51:57

If you are a web developer, the chances are that you have heard someone talking about React. After hearing about it for months, I found myself thinking what exactly is React and how the heck do I get started with it? 

Here is what I know so far for those of you who want to start experimenting with React. 

By the end of this blog, you will be able to:
- explain what React is and what are the benefits of using it
- build a simple React app that fetches data from a third party API and render information on a page
- add or remove an item from a page

####Additional Resources
1. Background info on React
I will be mentioning React jargons and concepts throughout the blog. If you need further explanations, checkout [Vumbala React e-book](https://medium.com/the-andela-way/a-beginners-guide-to-react-with-es6-a2ed0b5c977e). I found this resource to be very helpful when I began learning about React. 

2. API used in this tutorial
If you want to take a closer look at the data structure of the API we are using, check it out [here](https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=Gin).

Let's get started!

####What is React and its benefits?
React is a JavaScript library for building user interfaces. 

With React, you can: 
1. speed up your web app
React is known for its speed as it uses virtual DOM. This makes your web app work a lot faster than the ones built with Vanilla JavaScript. 

2. create reusable web components
Reusable web components not only reduces your workload, it makes your code easier to read as you can take huge lines of code and put them into components.

3. benefit from actively maintained Open Source JavaScript library
React is maintained by Facebook. Since React is so popular, there is a huge community of developers who actively contribute to it. There is a ton of resources for you to sink your teeth into as you begin your journey with React.

4. make yourself more marketable
React is high in demand. Becoming an expert in React will make you very marketable whether you are looking for a new job or looking for collaborators for your next project. 

#### Creating your first React app
After exterminating bugs in your code all day, there is nothing more relaxing then kicking back with a well crafted cocktail. 

Let's create a React app that displays cocktails!

This app is divided into two sections:
1.Favorites section that displays all of the cocktails you have added as your favorites. 
2.Cocktails section that displays all of the available cocktails. 

**End product demo**

![cocktailApp]
(https://user-images.githubusercontent.com/60980933/85240673-332aef80-b3f6-11ea-9b31-c2827894e643.gif)

When you click on a cocktail card in the Cocktails section, it adds that card to your Favorites section. 

Notice that this app is designed to avoid displaying duplicate cocktail cards in the Favorites section. When you click on the same card twice, the app will add the card to the Favorites section only once. 

You can remove a favorite by clicking on the card displayed in your Favorites section.  

####Step 1: Create a React app
To install React globally, run the following command in your terminal.
```Ruby
npm install-g create-react app
```
Then, type create-react-app followed by the name of your app as shown below.
```Ruby
create-react-app cocktail-app
```
If you do not wish to have React installed globally, type in the following in your terminal to create a React app. 
```Ruby
npx create-react-app cocktail-app
```
Once the React app has been created, change into cocktail-app directory and open it up in your editor. 
```Ruby
cd cocktail-app
code .
```
####Step 2: Start React app
Start the app by typing the following command. 
```Ruby
npm start
```
####Step 3: Copy and paste the following code in App.css
Although this blog will not be focus on styling, I have provided css code here so you can replicate the styling shown in the end product demo. 
```Ruby
#App.css

.App {
  text-align: center;
}

.cocktail-list {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  list-style-type: none;
}

.favorite-list {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  height: 400px;
  background-color: rgb(253,180, 70);
  list-style-type: none;
}

.card {
  width: 300px;
  height: 350 px;
  box-shadow: 0 6px 15px 6px rgb(211,211,211);
  margin-bottom: 40px;
}

.card img{
  width: 100%
}
```
####Step 4: Decide on the organization of components
One of the benefits of using React is that you can create reusable components responsible for different tasks. This feature allows you to separate your concerns and make your code easier to read and debug!

The way you organize your components is dependent on your preference or complexity of your project.  

For our purpose, we will separate the components into three parts.

1. App.js
This component handles all of our logic and states.

2. Display.js
This component divides the page into two sections(Cocktails and Favorites).

3. CocktailCard.js
This component handles what information cocktail card displays and how the card will behave once user clicks on the card. 

####Step 5: Create components 
In your text editor, you will see a directory called src.

When you expand the directory, you will see that App.js and App.css files have already been created for you. 

At the same level of App.js, create a folder called components.
Within components folder, create CocktailCard.js and Display.js files as shown below. 

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

####Step 6: Add state and logic to App.js
Copy and paste the following to your App.js. I will be explaining the code line by line below!

```Ruby
#App.js
import React from "react";
import CocktailCard from "./components/CocktailCard";
import Display from "./components/Display"
import "./App.css"

class App extends React.Component {
  state = {
    cocktails: [],
    favorites: [],
  };

  componentDidMount() {
    fetch("https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=gin")
      .then((response) => response.json())
      .then((response) =>
        this.setState({
          cocktails: response.drinks,
        })
      );
  }

  showCocktails = () => {
    return this.state.cocktails.map((cocktail) => (
      <CocktailCard key={cocktail.id} addToFavorites ={this.addToFavorites} cocktail={cocktail} />
    ));
  };

  showFavorites = () => {
    return this.state.favorites.map((cocktail) => (
      <CocktailCard key={cocktail.id} removeFromFavorites ={this.removeFromFavorites} cocktail={cocktail} />
    ));
  };

  addToFavorites =(cocktail)=>{
      if(!this.state.favorites.find(drink=>drink.idDrink === cocktail.idDrink))
      this.setState({
          favorites: [...this.state.favorites, cocktail]
      })
  }

  removeFromFavorites =(cocktail)=>{
    const filtered = this.state.favorites.filter(drink=>drink.idDrink !== cocktail.idDrink)
    this.setState({
        favorites: filtered
    })
}

  render() {
    return (
     <Display showCocktails ={this.showCocktails} showFavorites = {this.showFavorites}/>
    );
  }
}
export default App;
```
Let's break this down!

**lines 1-4**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wedjgag8fid9jbbwjl3r.png)
We are importing the React library, CocktailCard component, Display component, and App.css. We need to import these components as we will be incorporating these components into the functions we write in App.js

**-lines 6-10**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/h5d7gedt9hbm8d95tq6t.png)
We are managing state in our App component. Since we are not using Hooks, we are making our App component to be a class component. 

State will be managing two properties(cocktails and favorites). We set these to empty arrays, as state of these two properties will be fluctuating based on user behavior. 

**lines 12-20**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8hjlq6u820ixzzp4muxv.png)
componentDidMount is a life cycle method that runs once the component has been rendered to the page. 

Within componentDidMount, we make a fetch request to a third party API then we parse the response. The response is an array of cocktail objects fetched from the API that can be accessed with a key of drinks. 

Then, we set the state of property cocktails and set its value to an array of cocktail objects fetched from the API.

These cocktail objects contain data about cocktail name and image we will use to create individual cocktail cards. We will display these cards on the page. 

**lines 22-26**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ucv0w668tp5ohot249k6.png)
Our page is divided into two sections(Cocktails and Favorites). 

showCocktails function handles what gets displayed in the Cocktails section. 

This function maps through cocktails property set in the previous step. For every cocktail, it creates an individual cocktail card. 

In step 3, we decided that App component will manage all logic and state of our app. CocktailCard component will control what info cocktail card will contain and how the app is going to behave once the user clicks on a card. 

In order for CocktailCard component to fulfill its duties, it needs relevant data and functions being managed by the App component. We accomplish this by passing the data and functions to CocktailCard component as props (line 24). 

**Let's breakdown line 24.**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/imi6em7u2xj3ao43lqcq.png)

We are passing in key, addToFavorites function which we define later, and cocktail as props to CocktailCard component. 

The key attribute gives your element a unique identity. You need to include the key because React needs to know how elements are going to be treated in the virtual DOM. When you do not include the key, you will see the following error in your console.
```
Each child in an array or iterator should have a unique "key" prop.
```
For further explanation on why you need to include a unique key prop, check out this [blog](https://medium.com/@nothingisfunny/keys-and-refs-in-react-fd954457fd75).

The cocktail props contains info about individual cocktail name and image. This information is used by CocktailCard component to create a cocktail card that displays name and image of a cocktail. 

addTofavorites is a function we will define shortly. This function will help CocktailCard component to add a cocktail card to favorites section once the card has been clicked. We will delve more into this function in lines 34-39. 

**lines 28-32**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vezg744nix3wgzgigtpy.png)
showFavorites function is very similar to showCocktails function. This function shows all cocktails we have added to the favorites section. We are mapping through array of favorites that state holds. For each cocktail, we create a cocktail card.
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xim1eca1bfvhhwppjute.png)
In line 30, we are passing in a key, removeFromFavorites function which we define later, and cocktail as props to CocktailCard component. 

removeFromfavorites is a function we will define shortly. This function will help CocktailCard component to remove a cocktail card from favorites section once the card has been clicked. We will delve more into this function in lines 41-47. 

**lines 34-39**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/16pioxavnphsd3tfyvun.png)
addToFavorites function assists CocktailCard component. When a user clicks on a cocktail card, it adds that card to the Favorites section.

addtoFavorites function does that by:
1. grabbing the cocktail that user clicks on and
2. setting the state of favorites property so that it includes all of the cocktails that have been added to the favorites beforehand PLUS the cocktail that user just clicked on (lines 36-37).

The showFavorites function we have defined earlier(lines 28-32), will then map through the new Favorites state and create cocktail cards for display in the favorites section. 

Remember that our app is designed to avoid displaying duplicate cocktail cards in the Favorites section. When you click on the same card twice, the app will add the card to the Favorites section only once.
 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/j1t3gqknrrrv563d1y8l.png)

Line 35 allows us to accomplish this task. It says:
1. identify the id of the drink user clicked on (drink.idDrink)
2. Go through the Favorites state to make sure we do not already have that drink in our favorites section 
3. Only if we do not have that drink in our favorites state, THEN add the cocktail to the Favorites state(line 36).

**lines 41-47**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ux8ff5cd73uobb4qbpgu.png)
We are creating a function that allows you to remove a cocktail from your favorites. 

In line 42, we filter through the favorites state. We identify cocktail cards that do not have the same id as the card clicked on by user. 

In lines 43 -44, we set the state of favorites with the filtered cards from line 42. 

Now, when a user clicks on the card from the favorites section, it only displays favorite cards that have not been clicked by the user. 

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

We have App.js render Display component, as this component is responsible for displaying Favorites and Cocktails sections to the page. 

We pass showCocktails function and showFavorites function to the Display component as we will be using these functions to display Cocktails and Favorites Sections on the page. 

####Step 7: Configure Display.js to handle the display of cocktails and favorites section on the page
```Ruby
#Display.js

import React from "react"

function Display ({showFavorites, showCocktails}) {
    return(
        <div className="App">
        <h1> Cocktail Hour </h1>
        <section>
          <h1>Favorites</h1>
          <ul className="favorite-list">{showFavorites()}</ul>
        </section>
        <section>
          <h1>Cocktails</h1>
          <ul className="cocktail-list">{showCocktails()}</ul>
        </section>
      </div>
    )
}
export default Display
```
**line 1**
import React library

**line 3**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k3fbme8dr9mrgjtydx5q.png)
We create a functional component for Display.js as we do not need to handle state here. 

Remember we passed showFavorites and showCocktail functions as props from App component to Display component. We deconstruct props showFavorites and showCocktails functions to eliminate the need to write props. before these functions. 

**lines 5-15**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zgtaanggnr8uu3gvtdj6.png)
The end product shown at the beginning of this blog displays Cocktail hour header followed by two different sections: Favorites section and Cocktails section.

Within each section, there are descriptive header and unordered list that calls showFavorites/showCocktails functions we passed as props from App.js.

Notice that while showFavorites and showCocktails functions have been defined in App.js, these functions are called in Display component(lines 9 and 13). 

**line 18**
We export Display as we need to access this component in App.js

####Step 8: Configure CocktailCard.js to handle information and behavior exhibited by the card 
```Ruby
import React from "react";

function CocktailCard({ cocktail, addToFavorites, removeFromFavorites }) {
  const handleChange = () => {
    if (addToFavorites) {
      addToFavorites(cocktail);
    } else {
      removeFromFavorites(cocktail);
    }
  };
  return (
    <li className="card" onClick={handleChange}>
      <h3>{cocktail.strDrink}</h3>
      <img src={cocktail.strDrinkThumb} />
    </li>
  );
}
export default CocktailCard;
```
**line 1**
Import React library

**line 3**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gpzei4zhlnqe42bp8ckj.png)
Create a functional component as we are not handling states.

Remember that we passed props cocktail, addToFavorites, and removeFavorites from App component to CocktailCard component. Deconstruct props cocktail, addToFavorites, removeFromFavorites to eliminate the need to write props. before these functions. 

**lines 11-17**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y7urhtg09qosa21xkvze.png)
Every card is an li that contains a header that includes the name of the cocktail(line 13) and image of the cocktail(line 14). 
Add an onClick event handler that calls function handleChange when a user clicks on the card. 

**lines-4-10**
Remember that CocktailCards component handles cards shown in both the Favorites section and Cocktail section. It also handles how the card behaves when a user clicks on the card. 

Let's refer back to the code we have previously written in App.js.
The cards displayed in Cocktails section receives props addToFavorites.
```
# App.js

 showCocktails = () => {
    return this.state.cocktails.map((cocktail) => (
      <CocktailCard key={cocktail.id} addToFavorites ={this.addToFavorites} cocktail={cocktail} />
    ));
  };
```
The cards displayed in Favorites section receives props removeFromFavorites. 
```
#App.js
 showFavorites = () => {
    return this.state.favorites.map((cocktail) => (
      <CocktailCard key={cocktail.id} removeFromFavorites ={this.removeFromFavorites} cocktail={cocktail} />
    ));
  };
```
Therefore, cards in favorites section receive addToFavorites as props whereas cards in cocktails section receive removeFromFavorites as props. 

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

Line 5 is saying that when a user clicks the card, check for its props. If that card contains props addToFavorites, then run addToFavorites function. This will add a card to the Favorites section. 

Else, run the removeFromFavorites function, which will remove the card from the Favorites section. 

**line 18**
export CocktailCard so other App component could access it.

There you have it! You've just created your very first React app following these 8 steps!
1. Create a React app
2. Start React app
3. Set up Styling
4. Decide on the organization of components
5. Create components
6. Add state and logic to App.js
7. Configure Display.js to handle the display of cocktails and favorites section on the page
8. Configure CocktailCard.js to handle information and behavior exhibited by the card 

Now that you know the basics of creating a React app, go create your one of a kind app!