Repository: Asabeneh/30-Days-Of-React Branch: master Commit: 2bdabdf89672 Files: 257 Total size: 1.9 MB Directory structure: gitextract_bsi177zr/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── 01_Day_JavaScript_Refresher/ │ └── 01_javascript_refresher.md ├── 02_Day_Introduction_to_React/ │ └── 02_introduction_to_react.md ├── 03_Day_Setting_Up/ │ ├── 03_setting_up.md │ └── 03_setting_up_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── index.js │ └── math.js ├── 04_Day_Components/ │ ├── 04_components.md │ └── 04_components_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ └── index.js ├── 05_Day_Props/ │ ├── 05_props.md │ └── 05_props_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ └── index.js ├── 06_Day_Map_List_Keys/ │ ├── 06_map_list_keys.md │ └── 06_map_list_keys_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 07_Day_Class_Components/ │ ├── 07_class_based_components_boilerplate/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── data/ │ │ │ ├── countries.js │ │ │ └── ten_most_highest_populations.js │ │ └── index.js │ └── 07_class_components.md ├── 08_Day_States/ │ ├── 08_states.md │ └── 08_states_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 09_Day_Conditional_Rendering/ │ ├── 09_conditional_rendering.md │ └── 09_conditional_rendering_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 10_React_Project_Folder_Structure/ │ ├── 10_react_project_folder_structure.md │ └── 10_react_project_folder_structure_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── App.js │ ├── components/ │ │ ├── color/ │ │ │ └── HexaColor.js │ │ ├── country/ │ │ │ └── Country.js │ │ ├── footer/ │ │ │ └── Footer.js │ │ ├── header/ │ │ │ └── Header.js │ │ ├── main/ │ │ │ └── Main.js │ │ ├── shared/ │ │ │ └── Button.js │ │ └── user/ │ │ └── UserCard.js │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ ├── styles/ │ │ ├── button-styles.js │ │ ├── common.css │ │ ├── country.css │ │ ├── footer.css │ │ ├── header.css │ │ ├── index.css │ │ └── user-card.css │ └── utils/ │ ├── display-date-and-time.js │ └── hexadecimal-color-generator.js ├── 11_Day_Events/ │ ├── 11_events.md │ └── 11_events_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 12_Day_Forms/ │ ├── 12_forms.md │ └── 12_forms_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 13_Day_Controlled_Versus_Uncontrolled_Input/ │ ├── 13_uncontrolled_input.md │ └── 13_uncontrolled_input_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 14_Day_Component_Life_Cycles/ │ ├── 14_component_life_cycles.md │ └── 14_component_life_cycles_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 15_Third_Party_Packages/ │ ├── 15_third_party_packages.md │ └── 15_third_pary_packages_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 16_Higher_Order_Component/ │ ├── 16_higher_order_component.md │ └── 16_higher_order_component_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 17_React_Router/ │ ├── 17_react_router.md │ └── 17_react_router_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 18_Fetch_And_Axios/ │ ├── 18_fetch_and_axios_boilerplate/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── package.json │ │ ├── public/ │ │ │ └── index.html │ │ └── src/ │ │ ├── data/ │ │ │ ├── countries.js │ │ │ └── ten_most_highest_populations.js │ │ └── index.js │ └── 18_fetch_axios.md ├── 19_projects/ │ ├── 19_projects.md │ └── 19_projects_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 20_projects/ │ ├── 20_projects.md │ └── 20_projects_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ └── index.js ├── 21_Introducing_Hooks/ │ ├── 21_introducing_hooks.md │ └── 21_introducing_hooks_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ └── index.scss ├── 22_Form_Using_Hooks/ │ ├── 22_form_using_hooks.md │ └── 22_form_using_hooks_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ └── index.scss ├── 23_Fetching_Data_Using_Hooks/ │ ├── 23_fetching_data_using_hooks.md │ └── 23_fetching_data_using_hooks_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ └── index.scss ├── 24_projects/ │ ├── 24_projects.md │ └── 24_projects_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ └── index.scss ├── 25_Custom_Hooks/ │ ├── 25_custom_hooks.md │ └── 25_custom_hooks_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ ├── index.scss │ └── useFetch.js ├── 26_Context/ │ ├── 26_context.md │ └── 26_context_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ ├── index.scss │ └── useFetch.js ├── 27_Ref/ │ ├── 27_ref.md │ └── 27_ref_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ ├── index.scss │ └── useFetch.js ├── 28_project/ │ ├── 28_project.md │ └── 28_project_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ ├── index.scss │ └── useFetch.js ├── 29_explore/ │ ├── 29_explore.md │ └── 29_explore_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ ├── index.scss │ └── useFetch.js ├── 30_conclusions/ │ ├── 30_conclusions.md │ └── 30_conclusions_boilerplate/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── data/ │ │ ├── countries.js │ │ └── ten_most_highest_populations.js │ ├── index.js │ ├── index.scss │ └── useFetch.js └── readMe.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: [Asabeneh] thanks_dev: custom: [] # These are supported funding model platforms # github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] # patreon: # Replace with a single Patreon username # open_collective: # Replace with a single Open Collective username # ko_fi: # Replace with a single Ko-fi username # tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel # community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry # liberapay: # Replace with a single Liberapay username # issuehunt: # Replace with a single IssueHunt username # lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry # polar: # Replace with a single Polar username # buy_me_a_coffee: # Replace with a single Buy Me a Coffee username # thanks_dev: # Replace with a single thanks.dev username # custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .gitignore ================================================ draft.md react-for-everyone.md component.md draft ================================================ FILE: 01_Day_JavaScript_Refresher/01_javascript_refresher.md ================================================

30 Days Of React: JavaScript Refresher

Twitter Follow Author: Asabeneh Yetayeh
October, 2020
[<< Day 0](../readMe.md) | [Day 2 >>](../02_Day_Introduction_to_React/02_introduction_to_react.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_1.jpg) - [JavaScript Refresher](#javascript-refresher) - [0. Adding JavaScript to a Web Page](#0-adding-javascript-to-a-web-page) - [Inline Script](#inline-script) - [Internal Script](#internal-script) - [External Script](#external-script) - [Multiple External Scripts](#multiple-external-scripts) - [1. Variables](#1-variables) - [2. Data types](#2-data-types) - [3. Arrays](#3-arrays) - [How to create an empty array](#how-to-create-an-empty-array) - [How to create an array with values](#how-to-create-an-array-with-values) - [Creating an array using split](#creating-an-array-using-split) - [Accessing array items using index](#accessing-array-items-using-index) - [Modifying array element](#modifying-array-element) - [Methods to manipulate array](#methods-to-manipulate-array) - [Array Constructor](#array-constructor) - [Creating static values with fill](#creating-static-values-with-fill) - [Concatenating array using concat](#concatenating-array-using-concat) - [Getting array length](#getting-array-length) - [Getting index of an element in an array](#getting-index-of-an-element-in-an-array) - [Getting last index of an element in array](#getting-last-index-of-an-element-in-array) - [Checking array](#checking-array) - [Converting array to string](#converting-array-to-string) - [Joining array elements](#joining-array-elements) - [Slice array elements](#slice-array-elements) - [Splice method in array](#splice-method-in-array) - [Adding item to an array using push](#adding-item-to-an-array-using-push) - [Removing the end element using pop](#removing-the-end-element-using-pop) - [Removing an element from the beginning](#removing-an-element-from-the-beginning) - [Add an element from the beginning](#add-an-element-from-the-beginning) - [Reversing array order](#reversing-array-order) - [Sorting elements in array](#sorting-elements-in-array) - [Array of arrays](#array-of-arrays) - [💻 Exercise](#-exercise) - [Exercise: Level 1](#exercise-level-1) - [Exercise: Level 2](#exercise-level-2) - [Exercise: Level 3](#exercise-level-3) - [4. Conditionals](#4-conditionals) - [If](#if) - [If Else](#if-else) - [If Else if Else](#if-else-if-else) - [Switch](#switch) - [Ternary Operators](#ternary-operators) - [💻 Exercises](#-exercises) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) - [5. Loops](#5-loops) - [Types of Loops](#types-of-loops) - [1. for](#1-for) - [2. while](#2-while) - [3. do while](#3-do-while) - [4. for of](#4-for-of) - [5. forEach](#5-foreach) - [6. for in](#6-for-in) - [Interrupting a loop and skipping an item](#interrupting-a-loop-and-skipping-an-item) - [break](#break) - [continue](#continue) - [Conclusions](#conclusions) - [6. Scope](#6-scope) - [Window Scope](#window-scope) - [Global scope](#global-scope) - [Local scope](#local-scope) - [7. Object](#7-object) - [Creating an empty object](#creating-an-empty-object) - [Creating an objecting with values](#creating-an-objecting-with-values) - [Getting values from an object](#getting-values-from-an-object) - [Creating object methods](#creating-object-methods) - [Setting new key for an object](#setting-new-key-for-an-object) - [Object Methods](#object-methods) - [Getting object keys using Object.keys()](#getting-object-keys-using-objectkeys) - [Getting object values using Object.values()](#getting-object-values-using-objectvalues) - [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries) - [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty) - [💻 Exercises](#-exercises-1) - [Exercises: Level 1](#exercises-level-1-1) - [Exercises: Level 2](#exercises-level-2-1) - [Exercises: Level 3](#exercises-level-3-1) - [8. Functions](#8-functions) - [Function Declaration](#function-declaration) - [Function without a parameter and return](#function-without-a-parameter-and-return) - [Function returning value](#function-returning-value) - [Function with a parameter](#function-with-a-parameter) - [Function with two parameters](#function-with-two-parameters) - [Function with many parameters](#function-with-many-parameters) - [Function with unlimited number of parameters](#function-with-unlimited-number-of-parameters) - [Unlimited number of parameters in regular function](#unlimited-number-of-parameters-in-regular-function) - [Unlimited number of parameters in arrow function](#unlimited-number-of-parameters-in-arrow-function) - [Anonymous Function](#anonymous-function) - [Expression Function](#expression-function) - [Self Invoking Functions](#self-invoking-functions) - [Arrow Function](#arrow-function) - [Function with default parameters](#function-with-default-parameters) - [Function declaration versus Arrow function](#function-declaration-versus-arrow-function) - [💻 Exercises](#-exercises-2) - [Exercises: Level 1](#exercises-level-1-2) - [Exercises: Level 2](#exercises-level-2-2) - [Exercises: Level 3](#exercises-level-3-2) - [9. Higher Order Function](#9-higher-order-function) - [Callback](#callback) - [Returning function](#returning-function) - [setting time](#setting-time) - [setInterval](#setinterval) - [setTimeout](#settimeout) - [10. Destructuring and Spreading](#10-destructuring-and-spreading) - [What is Destructuring?](#what-is-destructuring) - [What can we destructure?](#what-can-we-destructure) - [1. Destructuring arrays](#1-destructuring-arrays) - [2. Destructuring objects](#2-destructuring-objects) - [Exercises](#exercises) - [Spread or Rest Operator](#spread-or-rest-operator) - [Spread operator to get the rest of array elements](#spread-operator-to-get-the-rest-of-array-elements) - [Spread operator to copy array](#spread-operator-to-copy-array) - [Spread operator to copy object](#spread-operator-to-copy-object) - [Spread operator with arrow function](#spread-operator-with-arrow-function) - [11. Functional Programming](#11-functional-programming) - [1. forEach](#1-foreach) - [2. map](#2-map) - [3. filter](#3-filter) - [4. reduce](#4-reduce) - [5. find](#5-find) - [6. findIndex](#6-findindex) - [7. some](#7-some) - [8. every](#8-every) - [Exercises](#exercises-1) - [12. Classes](#12-classes) - [Defining a classes](#defining-a-classes) - [Class Instantiation](#class-instantiation) - [Class Constructor](#class-constructor) - [Default values with constructor](#default-values-with-constructor) - [Class methods](#class-methods) - [Properties with initial value](#properties-with-initial-value) - [getter](#getter) - [setter](#setter) - [Static method](#static-method) - [Inheritance](#inheritance) - [Overriding methods](#overriding-methods) - [Exercises](#exercises-2) - [Exercises Level 1](#exercises-level-1-3) - [Exercises Level 2](#exercises-level-2-3) - [Exercises Level 3](#exercises-level-3-3) - [13 Document Object Model(DOM)](#13-document-object-modeldom) ## JavaScript Refresher ### 0. Adding JavaScript to a Web Page JavaScript can be added to a web page in three different ways: - **_Inline script_** - **_Internal script_** - **_External script_** - **_Multiple External scripts_** The following sections show different ways of adding JavaScript code to your web page. #### Inline Script Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_index.html_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/). ```html 30DaysOfScript:Inline Script ``` Now, you just wrote your first inline script. We can create a pop up alert message using the _alert()_ built-in function. #### Internal Script The internal script can be written in the _head_ or the _body_, but it is preferred to put it on the body of the HTML document. First, let us write on the head part of the page. ```html 30DaysOfScript:Internal Script ``` This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the console.log() ```html 30DaysOfScript:Internal Script ``` Open the browser console to see the output from the console.log() ![js code from vscode](../images/js_code_vscode.png) #### External Script Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body. First, we should create an external JavaScript file with .js extension. All files ending with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body. ```js console.log('Welcome to 30DaysOfJavaScript') ``` External scripts in the _head_: ```html 30DaysOfJavaScript:External script ``` External scripts in the _body_: ```html 30DaysOfJavaScript:External script //it could be in the header or in the body // Here is the recommended place to put the external script ``` Open the browser console to see the output of the console.log() #### Multiple External Scripts We can also link multiple external JavaScript files to a web page. Create a helloworld.js file inside the 30DaysOfJS folder and write the following code. ```js console.log('Hello, World!') ``` ```html Multiple External Scripts ``` _Your main.js file should be below all other scripts_. It is very important to remember this. ![Multiple Script](../images/multiple_script.png) ### 1. Variables We use _var_, _let_ and _const_ to declare a variable. The _var_ is functions scope, however _let_ and _const_ are block scope. In this challenge we use ES6 and above features of JavaScript. Avoid using _var_. ```js let firstName = 'Asabeneh' firstName = 'Eyob' const PI = 3.14 // Not allowed to reassign PI to a new value // PI = 3. ``` ### 2. Data types If you do not feel comfortable with data types check the following [link](https://github.com/Asabeneh/30-Days-Of-JavaScript/blob/master/02_Day_Data_types/02_day_data_types.md) ### 3. Arrays In contrast to variables, an array can store _multiple values_. Each value in an array has an _index_, and each index has _a reference in a memory address_. Each value can be accessed by using their _indexes_. The index of an array starts from _zero_, and the index of the last element is less by one from the length of the array. An array is a collection of different data types which are ordered and changeable(modifiable). An array allows storing duplicate elements and different data types. An array can be empty, or it may have different data type values. #### How to create an empty array In JavaScript, we can create an array in different ways. Let us see different ways to create an array. It is very common to use _const_ instead of _let_ to declare an array variable. If you are using const it means you do not use that variable name again. - Using Array constructor ```js // syntax const arr = Array() // or // let arr = new Array() console.log(arr) // [] ``` - Using square brackets([]) ```js // syntax // This the most recommended way to create an empty list const arr = [] console.log(arr) ``` #### How to create an array with values Array with initial values. We use _length_ property to find the length of an array. ```js const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of strings, fruits const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of strings, vegetables const animalProducts = ['milk', 'meat', 'butter', 'yoghurt'] // array of strings, products const webTechs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] // array of web technologies const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] // array of strings, countries // Print the array and its length console.log('Numbers:', numbers) console.log('Number of numbers:', numbers.length) console.log('Fruits:', fruits) console.log('Number of fruits:', fruits.length) console.log('Vegetables:', vegetables) console.log('Number of vegetables:', vegetables.length) console.log('Animal products:', animalProducts) console.log('Number of animal products:', animalProducts.length) console.log('Web technologies:', webTechs) console.log('Number of web technologies:', webTechs.length) console.log('Countries:', countries) console.log('Number of countries:', countries.length) ``` ```sh Numbers: [0, 3.14, 9.81, 37, 98.6, 100] Number of numbers: 6 Fruits: ['banana', 'orange', 'mango', 'lemon'] Number of fruits: 4 Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] Number of vegetables: 5 Animal products: ['milk', 'meat', 'butter', 'yoghurt'] Number of animal products: 4 Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] Number of web technologies: 7 Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] Number of countries: 5 ``` - Array can have items of different data types ```js const arr = [ 'Asabeneh', 250, true, { country: 'Finland', city: 'Helsinki' }, { skills: ['HTML', 'CSS', 'JS', 'React', 'Python'] }, ] // arr containing different data types console.log(arr) ``` #### Creating an array using split As we have seen in the earlier section, we can split a string at different positions, and we can change to an array. Let us see the examples below. ```js let js = 'JavaScript' const charsInJavaScript = js.split('') console.log(charsInJavaScript) // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"] let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' const companies = companiesString.split(',') console.log(companies) // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"] let txt = 'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.' const words = txt.split(' ') console.log(words) // the text has special characters think how you can just get only the words // ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"] ``` #### Accessing array items using index We access each element in an array using their index. An array index starts from 0. The picture below clearly shows the index of each element in the array. ![arr index](../images/array_index.png) ```js const fruits = ['banana', 'orange', 'mango', 'lemon'] let firstFruit = fruits[0] // we are accessing the first item using its index console.log(firstFruit) // banana secondFruit = fruits[1] console.log(secondFruit) // orange let lastFruit = fruits[3] console.log(lastFruit) // lemon // Last index can be calculated as follows let lastIndex = fruits.length - 1 lastFruit = fruits[lastIndex] console.log(lastFruit) // lemon ``` ```js const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // set of numbers console.log(numbers.length) // => to know the size of the array, which is 6 console.log(numbers) // -> [0, 3.14, 9.81, 37, 98.6, 100] console.log(numbers[0]) // -> 0 console.log(numbers[5]) // -> 100 let lastIndex = numbers.length - 1 console.log(numbers[lastIndex]) // -> 100 ``` ```js const webTechs = [ 'HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node', 'MongoDB', ] // List of web technologies console.log(webTechs) // all the array items console.log(webTechs.length) // => to know the size of the array, which is 7 console.log(webTechs[0]) // -> HTML console.log(webTechs[6]) // -> MongoDB let lastIndex = webTechs.length - 1 console.log(webTechs[lastIndex]) // -> MongoDB ``` ```js const countries = [ 'Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Ireland', 'Japan', 'Kenya', ] // List of countries console.log(countries) // -> all countries in array console.log(countries[0]) // -> Albania console.log(countries[10]) // -> Kenya let lastIndex = countries.length - 1 console.log(countries[lastIndex]) // -> Kenya ``` ```js const shoppingCart = [ 'Milk', 'Mango', 'Tomato', 'Potato', 'Avocado', 'Meat', 'Eggs', 'Sugar', ] // List of food products console.log(shoppingCart) // -> all shoppingCart in array console.log(shoppingCart[0]) // -> Milk console.log(shoppingCart[7]) // -> Sugar let lastIndex = shoppingCart.length - 1 console.log(shoppingCart[lastIndex]) // -> Sugar ``` #### Modifying array element An array is mutable(modifiable). Once an array is created, we can modify the contents of the array elements. ```js const numbers = [1, 2, 3, 4, 5] numbers[0] = 10 // changing 1 at index 0 to 10 numbers[1] = 20 // changing 2 at index 1 to 20 console.log(numbers) // [10, 20, 3, 4, 5] const countries = [ 'Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Ireland', 'Japan', 'Kenya', ] countries[0] = 'Afghanistan' // Replacing Albania by Afghanistan let lastIndex = countries.length - 1 countries[lastIndex] = 'Korea' // Replacing Kenya by Korea console.log(countries) ``` ```sh ["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"] ``` #### Methods to manipulate array There are different methods to manipulate an array. These are some of the available methods to deal with arrays:_Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_ ##### Array Constructor Array:To create an array. ```js const arr = Array() // creates an an empty array console.log(arr) const eightEmptyValues = Array(8) // it creates eight empty values console.log(eightEmptyValues) // [empty x 8] ``` ##### Creating static values with fill fill: Fill all the array elements with a static value ```js const arr = Array() // creates an an empty array console.log(arr) const eightXvalues = Array(8).fill('X') // it creates eight element values filled with 'X' console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X'] const eight0values = Array(8).fill(0) // it creates eight element values filled with '0' console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0] const four4values = Array(4).fill(4) // it creates 4 element values filled with '4' console.log(four4values) // [4, 4, 4, 4] ``` ##### Concatenating array using concat concat:To concatenate two arrays. ```js const firstList = [1, 2, 3] const secondList = [4, 5, 6] const thirdList = firstList.concat(secondList) console.log(thirdList) // [1, 2, 3, 4, 5, 6] ``` ```js const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of fruits const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of vegetables const fruitsAndVegetables = fruits.concat(vegetables) // concatenate the two arrays console.log(fruitsAndVegetables) ``` ```sh ["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"] ``` ##### Getting array length Length:To know the size of the array ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.length) // -> 5 is the size of the array ``` ##### Getting index of an element in an array indexOf:To check if an item exist in an array. If it exists it returns the index else it returns -1. ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.indexOf(5)) // -> 4 console.log(numbers.indexOf(0)) // -> -1 console.log(numbers.indexOf(1)) // -> 0 console.log(numbers.indexOf(6)) // -> -1 ``` Check an element if it exist in an array. - Check items in a list ```js // let us check if a banana exist in the array const fruits = ['banana', 'orange', 'mango', 'lemon'] let index = fruits.indexOf('banana') // 0 if (index != -1) { console.log('This fruit does exist in the array') } else { console.log('This fruit does not exist in the array') } // This fruit does exist in the array // we can use also ternary here index != -1 ? console.log('This fruit does exist in the array') : console.log('This fruit does not exist in the array') // let us check if a avocado exist in the array let indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1 if (indexOfAvocado != -1) { console.log('This fruit does exist in the array') } else { console.log('This fruit does not exist in the array') } // This fruit does not exist in the array ``` ##### Getting last index of an element in array lastIndexOf: It gives the position of the last item in the array. If it exist, it returns the index else it returns -1. ```js const numbers = [1, 2, 3, 4, 5, 3, 1, 2] console.log(numbers.lastIndexOf(2)) // 7 console.log(numbers.lastIndexOf(0)) // -1 console.log(numbers.lastIndexOf(1)) // 6 console.log(numbers.lastIndexOf(4)) // 3 console.log(numbers.lastIndexOf(6)) // -1 ``` includes:To check if an item exist in an array. If it exist it returns the true else it returns false. ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.includes(5)) // true console.log(numbers.includes(0)) // false console.log(numbers.includes(1)) // true console.log(numbers.includes(6)) // false const webTechs = [ 'HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node', 'MongoDB', ] // List of web technologies console.log(webTechs.includes('Node')) // true console.log(webTechs.includes('C')) // false ``` ##### Checking array Array.isArray:To check if the data type is an array ```js const numbers = [1, 2, 3, 4, 5] console.log(Array.isArray(numbers)) // true const number = 100 console.log(Array.isArray(number)) // false ``` ##### Converting array to string toString:Converts array to string ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.toString()) // 1,2,3,4,5 const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook ``` ##### Joining array elements join: It is used to join the elements of the array, the argument we passed in the join method will be joined in the array and return as a string. By default, it joins with a comma, but we can pass different string parameter which can be joined between the items. ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.join()) // 1,2,3,4,5 const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] console.log(names.join()) // Asabeneh,Mathias,Elias,Brook console.log(names.join('')) //AsabenehMathiasEliasBrook console.log(names.join(' ')) //Asabeneh Mathias Elias Brook console.log(names.join(', ')) //Asabeneh, Mathias, Elias, Brook console.log(names.join(' # ')) //Asabeneh # Mathias # Elias # Brook const webTechs = [ 'HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node', 'MongoDB', ] // List of web technologies console.log(webTechs.join()) // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB" console.log(webTechs.join(' # ')) // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB" ``` ##### Slice array elements Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position. ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.slice()) // -> it copies all item console.log(numbers.slice(0)) // -> it copies all item console.log(numbers.slice(0, numbers.length)) // it copies all item console.log(numbers.slice(1, 4)) // -> [2,3,4] // it doesn't include the ending position ``` ##### Splice method in array Splice: It takes three parameters:Starting position, number of times to be removed and number of items to be added. ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.splice()) // -> remove all items ``` ```js const numbers = [1, 2, 3, 4, 5] console.log(numbers.splice(0, 1)) // remove the first item ``` ```js const numbers = [1, 2, 3, 4, 5, 6] console.log(numbers.splice(3, 3, 7, 8, 9)) // -> [1, 2, 3, 7, 8, 9] //it removes three item and replace three items ``` ##### Adding item to an array using push Push: adding item in the end. To add item to the end of an existing array we use the push method. ```js // syntax const arr = ['item1', 'item2', 'item3'] arr.push('new item') console.log(arr) // ['item1', 'item2','item3','new item'] ``` ```js const numbers = [1, 2, 3, 4, 5] numbers.push(6) console.log(numbers) // -> [1,2,3,4,5,6] numbers.pop() // -> remove one item from the end console.log(numbers) // -> [1,2,3,4,5] ``` ```js let fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.push('apple') console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple'] fruits.push('lime') console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime'] ``` ##### Removing the end element using pop pop: Removing item in the end. ```js const numbers = [1, 2, 3, 4, 5] numbers.pop() // -> remove one item from the end console.log(numbers) // -> [1,2,3,4] ``` ##### Removing an element from the beginning shift: Removing one array element in the beginning of the array. ```js const numbers = [1, 2, 3, 4, 5] numbers.shift() // -> remove one item from the beginning console.log(numbers) // -> [2,3,4,5] ``` ##### Add an element from the beginning unshift: Adding array element in the beginning of the array. ```js const numbers = [1, 2, 3, 4, 5] numbers.unshift(0) // -> add one item from the beginning console.log(numbers) // -> [0,1,2,3,4,5] ``` ##### Reversing array order reverse: reverse the order of an array. ```js const numbers = [1, 2, 3, 4, 5] numbers.reverse() // -> reverse array order console.log(numbers) // [5, 4, 3, 2, 1] numbers.reverse() console.log(numbers) // [1, 2, 3, 4, 5] ``` ##### Sorting elements in array sort: arrange array elements in ascending order. Sort takes a call back function, we will see how we use sort with a call back function in the coming sections. ```js const webTechs = [ 'HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node', 'MongoDB', ] webTechs.sort() console.log(webTechs) // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"] webTechs.reverse() // after sorting we can reverse it console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"] ``` #### Array of arrays Array can store different data types including an array itself. Let us create an array of arrays ```js const firstNums = [1, 2, 3] const secondNums = [1, 4, 9] const arrayOfArray = [ [1, 2, 3], [1, 2, 3], ] console.log(arrayOfArray[0]) // [1, 2, 3] const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux'] const backEnd = ['Node', 'Express', 'MongoDB'] const fullStack = [frontEnd, backEnd] console.log(fullStack) // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]] console.log(fullStack.length) // 2 console.log(fullStack[0]) // ["HTML", "CSS", "JS", "React", "Redux"] console.log(fullStack[1]) // ["Node", "Express", "MongoDB"] ``` ### 💻 Exercise ##### Exercise: Level 1 ```js const countries = [ 'Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Ireland', 'Japan', 'Kenya', ] const webTechs = [ 'HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node', 'MongoDB', ] ``` 1. Declare an _empty_ array; 2. Declare an array with more than 5 number of elements 3. Find the length of your array 4. Get the first item, the middle item and the last item of the array 5. Declare an array called _mixedDataTypes_, put different data types in the array and find the length of the array. The array size should be greater than 5 6. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon 7. Print the array using _console.log()_ 8. Print the number of companies in the array 9. Print the first company, middle and last company 10. Print out each company 11. Change each company name to uppercase one by one and print them out 12. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies. 13. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is _not found_ 14. Filter out companies which have more than one 'o' without the filter method 15. Sort the array using _sort()_ method 16. Reverse the array using _reverse()_ method 17. Slice out the first 3 companies from the array 18. Slice out the last 3 companies from the array 19. Slice out the middle IT company or companies from the array 20. Remove the first IT company from the array 21. Remove the middle IT company or companies from the array 22. Remove the last IT company from the array 23. Remove all IT companies ##### Exercise: Level 2 1. Create a separate countries.js file and store the countries array into this file, create a separate file web_techs.js and store the webTechs array into this file. Access both file in main.js file 1. First remove all the punctuations and change the string to array and count the number of words in the array ```js let text = 'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.' console.log(words) console.log(words.length) ``` ```sh ["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"] 13 ``` 1. In the following shopping cart add, remove, edit items ```js const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey'] ``` - add 'Meat' in the beginning of your shopping cart if it has not been already added - add Sugar at the end of you shopping cart if it has not been already added - remove 'Honey' if you are allergic to honey - modify Tea to 'Green Tea' 1. In countries array check if 'Ethiopia' exists in the array if it exists print 'ETHIOPIA'. If it does not exist add to the countries list. 1. In the webTechs array check if Sass exists in the array and if it exists print 'Sass is a CSS preprocess'. If it does not exist add Sass to the array and print the array. 1. Concatenate the following two variables and store it in a fullStack variable. ```js const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux'] const backEnd = ['Node', 'Express', 'MongoDB'] console.log(fullStack) ``` ```sh ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] ``` ##### Exercise: Level 3 1. The following is an array of 10 students ages: `js const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] ` - Sort the array and find the min and max age - Find the median age(one middle item or two middle items divided by two) - Find the average age(all items divided by number of items) - Find the range of the ages(max minus min) - Compare the value of (min - average) and (max - average), use _abs()_ method 1.Slice the first ten countries from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) 1. Find the middle country(ies) in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) 1. Divide the countries array into two equal arrays if it is even. If countries array is not even , one more country for the first half. ### 4. Conditionals Conditional statements are used for make decisions based on different conditions. By default , statements in JavaScript script executed sequentially from top to bottom. If the processing logic require so, the sequential flow of execution can be altered in two ways: - Conditional execution: a block of one or more statements will be executed if a certain expression is true - Repetitive execution: a block of one or more statements will be repetitively executed as long as a certain expression is true. In this section, we will cover _if_, _else_ , _else if_ statements. The comparison and logical operators we learned in the previous sections will be useful in here. Conditions can be implementing using the following ways: - if - if else - if else if else - switch - ternary operator #### If In JavaScript and other programming languages the key word _if_ is to used check if a condition is true and to execute the block code. To create an if condition, we need _if_ keyword, condition inside a parenthesis and block of code inside a curly bracket({}). ```js // syntax if (condition) { //this part of code runs for truthy condition } ``` **Example:** ```js let num = 3 if (num > 0) { console.log(`${num} is a positive number`) } // 3 is a positive number ``` As you can see in the condition example above, 3 is greater than 0, so it is a positive number. The condition was true and the block of code was executed. However, if the condition is false, we won't see any results. ```js let isRaining = true if (isRaining) { console.log('Remember to take your rain coat.') } ``` The same goes for the second condition, if isRaining is false the if block will not be executed and we do not see any output. In order to see the result of a falsy condition, we should have another block, which is going to be _else_. #### If Else If condition is true the first block will be executed, if not the else condition will be executed. ```js // syntax if (condition) { // this part of code runs for truthy condition } else { // this part of code runs for false condition } ``` ```js let num = 3 if (num > 0) { console.log(`${num} is a positive number`) } else { console.log(`${num} is a negative number`) } // 3 is a positive number num = -3 if (num > 0) { console.log(`${num} is a positive number`) } else { console.log(`${num} is a negative number`) } // -3 is a negative number ``` ```js let isRaining = true if (isRaining) { console.log('You need a rain coat.') } else { console.log('No need for a rain coat.') } // You need a rain coat. isRaining = false if (isRaining) { console.log('You need a rain coat.') } else { console.log('No need for a rain coat.') } // No need for a rain coat. ``` The last condition is false, therefore the else block was executed. What if we have more than two conditions? In that case, we would use _else if_ conditions. #### If Else if Else On our daily life, we make decisions on daily basis. We make decisions not by checking one or two conditions instead we make decisions based on multiple conditions. As similar to our daily life, programming is also full of conditions. We use _else if_ when we have multiple conditions. ```js // syntax if (condition) { // code } else if (condition) { // code } else { // code } ``` **Example:** ```js let a = 0 if (a > 0) { console.log(`${a} is a positive number`) } else if (a < 0) { console.log(`${a} is a negative number`) } else if (a == 0) { console.log(`${a} is zero`) } else { console.log(`${a} is not a number`) } ``` ```js // if else if else let weather = 'sunny' if (weather === 'rainy') { console.log('You need a rain coat.') } else if (weather === 'cloudy') { console.log('It might be cold, you need a jacket.') } else if (weather === 'sunny') { console.log('Go out freely.') } else { console.log('No need for rain coat.') } ``` #### Switch Switch is an alternative for **if else if else else**. The switch statement starts with a _switch_ keyword followed by a parenthesis and code block. Inside the code block we will have different cases. Case block runs if the value in the switch statement parenthesis matches with the case value. The break statement is to terminate execution so the code execution does not go down after the condition is satisfied. The default block runs if all the cases don't satisfy the condition. ```js switch (caseValue) { case 1: // code break case 2: // code break case 3: // code default: // code } ``` ```js let weather = 'cloudy' switch (weather) { case 'rainy': console.log('You need a rain coat.') break case 'cloudy': console.log('It might be cold, you need a jacket.') break case 'sunny': console.log('Go out freely.') break default: console.log(' No need for rain coat.') } // Switch More Examples let dayUserInput = prompt('What day is today ?') let day = dayUserInput.toLowerCase() switch (day) { case 'monday': console.log('Today is Monday') break case 'tuesday': console.log('Today is Tuesday') break case 'wednesday': console.log('Today is Wednesday') break case 'thursday': console.log('Today is Thursday') break case 'friday': console.log('Today is Friday') break case 'saturday': console.log('Today is Saturday') break case 'sunday': console.log('Today is Sunday') break default: console.log('It is not a week day.') } ``` // Examples to use conditions in the cases ```js let num = prompt('Enter number') switch (true) { case num > 0: console.log('Number is positive') break case num == 0: console.log('Numbers is zero') break case num < 0: console.log('Number is negative') break default: console.log('Entered value was not a number') } ``` #### Ternary Operators Ternary operator is very common in _React_. It is a short way to write if else statement. In React we use ternary operator in many cases. To generalize, ternary operator is another way to write conditionals. ```js let isRaining = true isRaining ? console.log('You need a rain coat.') : console.log('No need for a rain coat.') ``` ### 💻 Exercises ##### Exercises: Level 1 1. Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:'You are old enough to drive' but if not 18 give another feedback stating to wait for the number of years he needs to turn 18. ```sh Enter your age: 30 You are old enough to drive. Enter your age:15 You are left with 3 years to drive. ``` 1. Compare the values of myAge and yourAge using if … else. Based on the comparison and log the result to console stating who is older (me or you). Use prompt(“Enter your age:”) to get the age as input. ```sh Enter your age: 30 You are 5 years older than me. ``` 1. If a is greater than b return 'a is greater than b' else 'a is less than b'. Try to implement it in two ways - using if else - ternary operator. ```js let a = 4 let b = 3 ``` ```sh 4 is greater than 3 ``` 1. Even numbers are divisible by 2 and the remainder is zero. How do you check, if a number is even or not using JavaScript? ```sh Enter a number: 2 2 is an even number Enter a number: 9 9 is is an odd number. ``` ##### Exercises: Level 2 1. Write a code which can give grades to students according to theirs scores: - 80-100, A - 70-89, B - 60-69, C - 50-59, D - 0-49, F 1. Check if the season is Autumn, Winter, Spring or Summer. If the user input is : - September, October or November, the season is Autumn. - December, January or February, the season is Winter. - March, April or May, the season is Spring - June, July or August, the season is Summer 1. Check if a day is weekend day or a working day. Your script will take day as an input. ```sh What is the day today? Saturday Saturday is a weekend. What is the day today? saturDaY Saturday is a weekend. What is the day today? Friday Friday is a working day. What is the day today? FrIDAy Friday is a working day. ``` ##### Exercises: Level 3 1. Write a program which tells the number of days in a month. ```sh Enter a month: January January has 31 days. Enter a month: JANUARY January has 31 day Enter a month: February February has 28 days. Enter a month: FEbruary February has 28 days. ``` 1. Write a program which tells the number of days in a month, now consider leap year. ### 5. Loops In programming we use different loops to carry out repetitive tasks. Therefore, loop can help us to automate tedious and repetitive task. JavaScript has also different types of loops which we can use to work on repetitive task. Imagine if your are asked to print Hello world one thousand times without a loop, it may take an hour or two to do this tedious task. However, using loop we can print it in less than a second. Loops: - for - while - do while - for of - forEach - for in A loop usually goes until the condition gets false. But sometimes we like to interrupt the loop or skip an item during iteration. We use _break_ to interrupt the loop and _continue_ to skip an item during iteration. #### Types of Loops ##### 1. for We use for loop when we know how many iteration we go. Let's see the following example ```js // for loop syntax for (initialization, condition, increment/decrement) { code goes here } ``` This code prints from 0 to 5. ```js for (let i = 0; i < 6; i++) { console.log(i) } ``` For example if we want to sum all the numbers from 0 to 100. ```js let sum = 0 for (let i = 0; i < 101; i++) { sum += i } console.log(sum) ``` If we want to sum only even numbers: ```js let sum = 0 for (let i = 0; i < 101; i += 2) { sum += i } console.log(sum) // or another way let total = 0 for (let i = 0; i < 101; i++) { if (i % 2 == 0) { total += i } } console.log(total) ``` This code iterates through the array ```js const nums = [1, 2, 3, 4, 5] for (let i = 0; i < 6; i++) { console.log(nums[i]) } ``` This code prints 5 to 0. Looping in reverse order ```js for (let i = 5; i >= 0; i--) { console.log(i) } ``` The Code below can reverse an array. ```js const nums = [1, 2, 3, 4, 5] const lastIndex = nums.length - 1 const newArray = [] for (let i = lastIndex; i >= 0; i--) { newArray.push(nums[i]) } console.log(newArray) ``` ##### 2. while We use the while loop when we do not know how man iteration we go in advance. ```js let count = prompt('Enter a positive number: ') while (count > 0) { console.log(count) count-- } ``` ##### 3. do while Do while run at least once if the condition is true or false ```js let count = 0 do { console.log(count) count++ } while (count < 11) ``` The code below runs ones though the condition is false ```js let count = 11 do { console.log(count) count++ } while (count < 11) ``` While loop is the least important loop in many programming languages. ##### 4. for of The for of loop is very handy to use it with array. If we are not interested in the index of the array a for of loop is preferable to regular for loop or forEach loop. ```js const numbers = [1, 2, 3, 4, 5] for (const number of numbers) { console.log(number) } const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] for (const country of countries) { console.log(country.toUpperCase()) } ``` ##### 5. forEach If we are interested in the index of the array forEach is preferable to for of loop. The forEach array method takes a callback function, the callback function takes three arguments: the item, the index and the array itself. ```js const numbers = [1, 2, 3, 4, 5] numbers.forEach((number, i) => { console.log(number, i) }) const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] countries.forEach((country, i, arr) => { console.log(i, country.toUpperCase()) }) ``` ##### 6. for in The for in loop can be used with object literals to get the keys of the object. ```js const user = { firstName: 'Asabeneh', lastName: 'Yetayeh', age: 250, country: 'Finland', skills: ['HTML', 'CSS', 'JS', 'React', 'Node', 'Python', 'D3.js'], } for (const key in user) { console.log(key, user[key]) } ``` #### Interrupting a loop and skipping an item ##### break Break is used to interrupt a loop. ```js for (let i = 0; i <= 5; i++) { if (i == 3) { break } console.log(i) } // 0 1 2 ``` The above code stops if 3 found in the iteration process. ##### continue We use the keyword continue to skip a certain iterations. ```js for (let i = 0; i <= 5; i++) { if (i == 3) { continue } console.log(i) } // 0 1 2 4 5 ``` #### Conclusions - Regular for loop can be used anywhere when the number of iteration is known. - While loop when the number of iteration is not know - Do while loop and while loop are almost the same but do while loop run at least once even when the condition is false - for of is used only for array - forEach is used for array - for in is used for object ### 6. Scope Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word _var_, _let_ and _const_. A variable can declared at different scope. In this section we will see the scope, scope of variables when we use var or let. Variables scopes can be: - Window - Global - Local Variable can be declared globally or locally or window scope. We will see both global and local scope. Anything declared without let, var or const is scoped at window level. Let us image we have a scope.js file. #### Window Scope Without using console.log() open your browser and check, you will see the value of a and b if you write a or b on the browser. That means a and b are already available in the window. ```js //scope.js a = 'JavaScript' // is a window scope this found anywhere b = 10 // this is a window scope variable function letsLearnScope() { console.log(a, b) if (true) { console.log(a, b) } } console.log(a, b) // accessible ``` #### Global scope A globally declared variable can be accessed every where in the same file. But the term global is relative. It can be global to the file or it can be global relative to some block of codes. ```js //scope.js let a = 'JavaScript' // is a global scope it will be found anywhere in this file let b = 10 // is a global scope it will be found anywhere in this file function letsLearnScope() { console.log(a, b) // JavaScript 10, accessible if (true) { let a = 'Python' let b = 100 console.log(a, b) // Python 100 } console.log(a, b) } letsLearnScope() console.log(a, b) // JavaScript 10, accessible ``` #### Local scope A variable declared as local can be accessed only in certain block code. ```js //scope.js let a = 'JavaScript' // is a global scope it will be found anywhere in this file let b = 10 // is a global scope it will be found anywhere in this file function letsLearnScope() { console.log(a, b) // JavaScript 10, accessible let c = 30 if (true) { // we can access from the function and outside the function but // variables declared inside the if will not be accessed outside the if block let a = 'Python' let b = 20 let d = 40 console.log(a, b, c) // Python 20 30 } // we can not access c because c's scope is only the if block console.log(a, b) // JavaScript 10 } letsLearnScope() console.log(a, b) // JavaScript 10, accessible ``` Now, you have an understanding of scope. A variable declared with _var_ only scoped to function but variable declared with _let_ or _const_ is block scope(function block, if block, loop etc). Block in JavaScript is a code in between two curly brackets ({}). ```js //scope.js function letsLearnScope() { var gravity = 9.81 console.log(gravity) } // console.log(gravity), Uncaught ReferenceError: gravity is not defined if (true) { var gravity = 9.81 console.log(gravity) // 9.81 } console.log(gravity) // 9.81 for (var i = 0; i < 3; i++) { console.log(i) // 1, 2, 3 } console.log(i) ``` In ES6 and above there is _let_ and _const_, so you will not suffer from the sneakiness of _var_. When we use _let_ our variable is block scoped and it will not infect other parts of our code. ```js //scope.js function letsLearnScope() { // you can use let or const, but gravity is constant I prefer to use const const gravity = 9.81 console.log(gravity) } // console.log(gravity), Uncaught ReferenceError: gravity is not defined if (true) { const gravity = 9.81 console.log(gravity) // 9.81 } // console.log(gravity), Uncaught ReferenceError: gravity is not defined for (let i = 0; i < 3; i++) { console.log(i) // 1, 2, 3 } // console.log(i), Uncaught ReferenceError: gravity is not defined ``` The scope _let_ and _const_ is the same. The difference is only reassigning. We can not change or reassign the value of const variable. I would strongly suggest you to use _let_ and _const_, by using _let_ and _const_ you will writ clean code and avoid hard to debug mistakes. As a rule of thumb, you can use _let_ for any value which change, _const_ for any constant value, and for array, object, arrow function and function expression. ### 7. Object Everything can be an object and objects do have properties and properties have values, so an object is a key value pair. The order of the key is not reserved, or there is no order. To create an object literal, we use two curly brackets. #### Creating an empty object An empty object ```js const person = {} ``` #### Creating an objecting with values Now, the person object has firstName, lastName, age, location, skills and isMarried properties. The value of properties or keys could be a string, number, boolean, an object, null, undefined or a function. Let us see some examples of object. Each key has a value in the object. ```js const rectangle = { length: 20, width: 20, } console.log(rectangle) // {length: 20, width: 20} const person = { firstName: 'Asabeneh', lastName: 'Yetayeh', age: 250, country: 'Finland', city: 'Helsinki', skills: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node', 'MongoDB', 'Python', 'D3.js', ], isMarried: true, } console.log(person) ``` #### Getting values from an object We can access values of object using two methods: - using . followed by key name if the key-name is a one word - using square bracket and a quote ```js const person = { firstName: 'Asabeneh', lastName: 'Yetayeh', age: 250, country: 'Finland', city: 'Helsinki', skills: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node', 'MongoDB', 'Python', 'D3.js', ], getFullName: function () { return `${this.firstName}${this.lastName}` }, 'phone number': '+3584545454545', } // accessing values using . console.log(person.firstName) console.log(person.lastName) console.log(person.age) console.log(person.location) // value can be accessed using square bracket and key name console.log(person['firstName']) console.log(person['lastName']) console.log(person['age']) console.log(person['age']) console.log(person['location']) // for instance to access the phone number we only use the square bracket method console.log(person['phone number']) ``` #### Creating object methods Now, the person object has getFullName properties. The getFullName is function inside the person object and we call it an object method. The _this_ key word refers to the object itself. We can use the word _this_ to access the values of different properties of the object. We can not use an arrow function as object method because the word this refers to the window inside an arrow function instead of the object itself. Example of object: ```js const person = { firstName: 'Asabeneh', lastName: 'Yetayeh', age: 250, country: 'Finland', city: 'Helsinki', skills: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node', 'MongoDB', 'Python', 'D3.js', ], getFullName: function () { return `${this.firstName} ${this.lastName}` }, } console.log(person.getFullName()) // Asabeneh Yetayeh ``` #### Setting new key for an object An object is a mutable data structure and we can modify the content of an object after it gets created. Setting a new keys in an object ```js const person = { firstName: 'Asabeneh', lastName: 'Yetayeh', age: 250, country: 'Finland', city: 'Helsinki', skills: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node', 'MongoDB', 'Python', 'D3.js', ], getFullName: function () { return `${this.firstName} ${this.lastName}` }, } person.nationality = 'Ethiopian' person.country = 'Finland' person.title = 'teacher' person.skills.push('Meteor') person.skills.push('SasS') person.isMarried = true person.getPersonInfo = function () { let skillsWithoutLastSkill = this.skills .slice(0, this.skills.length - 1) .join(', ') let lastSkill = this.skills.slice(this.skills.length - 1)[0] let skills = `${skillsWithoutLastSkill}, and ${lastSkill}` let fullName = this.getFullName() let statement = `${fullName} is a ${this.title}.\nHe lives in ${this.country}.\nHe teaches ${skills}.` return statement } console.log(person) console.log(person.getPersonInfo()) ``` ```sh Asabeneh Yetayeh is a teacher. He lives in Finland. He teaches HTML, CSS, JavaScript, React, Node, MongoDB, Python, D3.js, Meteor, and SasS. ``` #### Object Methods There are different methods to manipulate an object. Let us see some of the available methods. _Object.assign_: To copy an object without modifying the original object ```js const person = { firstName: 'Asabeneh', age: 250, country: 'Finland', city: 'Helsinki', skills: ['HTML', 'CSS', 'JS'], title: 'teacher', address: { street: 'Heitamienkatu 16', pobox: 2002, city: 'Helsinki', }, getPersonInfo: function () { return `I am ${this.firstName} and I live in ${this.city}, ${this.country}. I am ${this.age}.` }, } //Object methods: Object.assign, Object.keys, Object.values, Object.entries //hasOwnProperty const copyPerson = Object.assign({}, person) console.log(copyPerson) ``` ##### Getting object keys using Object.keys() _Object.keys_: To get the keys or properties of an object as an array ```js const keys = Object.keys(copyPerson) console.log(keys) //['name', 'age', 'country', 'skills', 'address', 'getPersonInfo'] const address = Object.keys(copyPerson.address) console.log(address) //['street', 'pobox', 'city'] ``` ##### Getting object values using Object.values() _Object.values_:To get values of an object as an array ```js const values = Object.values(copyPerson) console.log(values) ``` ##### Getting object keys and values using Object.entries() _Object.entries_:To get the keys and values in an array ```js const entries = Object.entries(copyPerson) console.log(entries) ``` ##### Checking properties using hasOwnProperty() _hasOwnProperty_: To check if a specific key or property exist in an object ```js console.log(copyPerson.hasOwnProperty('name')) console.log(copyPerson.hasOwnProperty('score')) ``` 🌕 You are astonishing. Now, you are super charged with the power of objects. You have just completed day 8 challenges and you are 8 steps a head into your way to greatness. Now do some exercises for your brain and for your muscle. ### 💻 Exercises ##### Exercises: Level 1 1. Create an empty object called dog 1. Print the the dog object on the console 1. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return _woof woof_ 1. Get name, legs, color, age and bark value from the dog object 1. Set new properties the dog object: breed, getDogInfo ##### Exercises: Level 2 1. Find the person who has many skills in the users object. 1. Count logged in users,count users having greater than equal to 50 points from the following object. ````js const users = { Alex: { email: 'alex@alex.com', skills: ['HTML', 'CSS', 'JavaScript'], age: 20, isLoggedIn: false, points: 30 }, Asab: { email: 'asab@asab.com', skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'], age: 25, isLoggedIn: false, points: 50 }, Brook: { email: 'daniel@daniel.com', skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], age: 30, isLoggedIn: true, points: 50 }, Daniel: { email: 'daniel@alex.com', skills: ['HTML', 'CSS', 'JavaScript', 'Python'], age: 20, isLoggedIn: false, points: 40 }, John: { email: 'john@john.com', skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], age: 20, isLoggedIn: true, points: 50 }, Thomas: { email: 'thomas@thomas.com', skills: ['HTML', 'CSS', 'JavaScript', 'React'], age: 20, isLoggedIn: false, points: 40 }, Paul: { email: 'paul@paul.com', skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'], age: 20, isLoggedIn: false, points: 40 } }``` ```` 1. Find people who are MERN stack developer from the users object 1. Set your name in the users object without modifying the original users object 1. Get all keys or properties of users object 1. Get all the values of users object 1. Use the countries object to print a country name, capital, populations and languages. ##### Exercises: Level 3 1. Create an object literal called _personAccount_. It has _firstName, lastName, incomes, expenses_ properties and it has _totalIncome, totalExpense, accountInfo,addIncome, addExpense_ and _accountBalance_ methods. Incomes is a set of incomes and its description and expenses is a set of incomes and its description. 2. \*\*\*\* Questions:2, 3 and 4 are based on the following two arrays:users and products () ```js const users = [ { _id: 'ab12ex', username: 'Alex', email: 'alex@alex.com', password: '123123', createdAt: '08/01/2020 9:00 AM', isLoggedIn: false, }, { _id: 'fg12cy', username: 'Asab', email: 'asab@asab.com', password: '123456', createdAt: '08/01/2020 9:30 AM', isLoggedIn: true, }, { _id: 'zwf8md', username: 'Brook', email: 'brook@brook.com', password: '123111', createdAt: '08/01/2020 9:45 AM', isLoggedIn: true, }, { _id: 'eefamr', username: 'Martha', email: 'martha@martha.com', password: '123222', createdAt: '08/01/2020 9:50 AM', isLoggedIn: false, }, { _id: 'ghderc', username: 'Thomas', email: 'thomas@thomas.com', password: '123333', createdAt: '08/01/2020 10:00 AM', isLoggedIn: false, }, ] const products = [ { _id: 'eedfcf', name: 'mobile phone', description: 'Huawei Honor', price: 200, ratings: [ { userId: 'fg12cy', rate: 5 }, { userId: 'zwf8md', rate: 4.5 }, ], likes: [], }, { _id: 'aegfal', name: 'Laptop', description: 'MacPro: System Darwin', price: 2500, ratings: [], likes: ['fg12cy'], }, { _id: 'hedfcg', name: 'TV', description: 'Smart TV:Procaster', price: 400, ratings: [{ userId: 'fg12cy', rate: 5 }], likes: ['fg12cy'], }, ] ``` Imagine you are getting the above users collection from a MongoDB database. a. Create a function called signUp which allows user to add to the collection. If user exists, inform the user that he has already an account. b. Create a function called signIn which allows user to sign in to the application 3. The products array has three elements and each of them has six properties. a. Create a function called rateProduct which rates the product b. Create a function called averageRating which calculate the average rating of a product 4. Create a function called likeProduct. This function will helps to like to the product if it is not liked and remove like if it was liked. ### 8. Functions So far we have seen many builtin JavaScript functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, lets understand what function is and why we need function? A function is a reusable block of code or programming statements designed to perform a certain task. A function is declared by a function key word followed by a name, followed by parentheses (). A parentheses can take a parameter. If a function take a parameter it will be called with argument. A function can also take a default parameter. To store a data to a function, a function has to return certain data types. To get the value we call or invoke a function. Function makes code: - clean and easy to read - reusable - easy to test A function can be declared or created in couple of ways: - _Declaration function_ - _Expression function_ - _Anonymous function_ - _Arrow function_ #### Function Declaration Let us see how to declare a function and how to call a function. ```js //declaring a function without a parameter function functionName() { // code goes here } functionName() // calling function by its name and with parentheses ``` #### Function without a parameter and return Function can be declared without a parameter. **Example:** ```js // function without parameter, a function which make a number square function square() { let num = 2 let sq = num * num console.log(sq) } square() // 4 // function without parameter function addTwoNumbers() { let numOne = 10 let numTwo = 20 let sum = numOne + numTwo console.log(sum) } addTwoNumbers() // a function has to be called by its name to be executed ``` ```js function printFullName() { let firstName = 'Asabeneh' let lastName = 'Yetayeh' let space = ' ' let fullName = firstName + space + lastName console.log(fullName) } printFullName() // calling a function ``` #### Function returning value Function can also return values, if a function does not return values the value of the function is undefined. Let us write the above functions with return. From now on, we return value to a function instead of printing it. ```js function printFullName() { let firstName = 'Asabeneh' let lastName = 'Yetayeh' let space = ' ' let fullName = firstName + space + lastName return fullName } console.log(printFullName()) ``` ```js function addTwoNumbers() { let numOne = 2 let numTwo = 3 let total = numOne + numTwo return total } console.log(addTwoNumbers()) ``` #### Function with a parameter In a function we can pass different data types(number, string, boolean, object, function) as a parameter. ```js // function with one parameter function functionName(parm1) { //code goes her } functionName(parm1) // during calling or invoking one argument needed function areaOfCircle(r) { let area = Math.PI * r * r return area } console.log(areaOfCircle(10)) // should be called with one argument function square(number) { return number * number } console.log(square(10)) ``` #### Function with two parameters ```js // function with two parameters function functionName(parm1, parm2) { //code goes her } functionName(parm1, parm2) // during calling or invoking two arguments needed // Function without parameter doesn't take input, so lets make a function with parameters function sumTwoNumbers(numOne, numTwo) { let sum = numOne + numTwo console.log(sum) } sumTwoNumbers(10, 20) // calling functions // If a function doesn't return it doesn't store data, so it should return function sumTwoNumbers(numOne, numTwo) { let sum = numOne + numTwo return sum } console.log(sumTwoNumbers(10, 20)) function printFullName(firstName, lastName) { return `${firstName} ${lastName}` } console.log(printFullName('Asabeneh', 'Yetayeh')) ``` #### Function with many parameters ```js // function with multiple parameters function functionName(parm1, parm2, parm3,...){ //code goes here } functionName(parm1,parm2,parm3,...) // during calling or invoking three arguments needed // this function takes array as a parameter and sum up the numbers in the array function sumArrayValues(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum; } const numbers = [1, 2, 3, 4, 5]; //calling a function console.log(sumArrayValues(numbers)); const areaOfCircle = (radius) => { let area = Math.PI * radius * radius; return area; } console.log(areaOfCircle(10)) ``` #### Function with unlimited number of parameters Sometimes we do not know how many arguments the user going to pass. Therefore, we should know how to write a function which can take unlimited number of arguments. The way we do it has a significant difference between a function declaration(regular function) and arrow function. Let us see examples both in function declaration and arrow function. ##### Unlimited number of parameters in regular function A function declaration provides a function scoped arguments array like object. Any thing we passed as argument in the function can be accessed from arguments object inside the functions. Let us see an example ```js // Let us access the arguments object ​ function sumAllNums() { console.log(arguments) } sumAllNums(1, 2, 3, 4)) // Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ] ``` ```js // function declaration ​ function sumAllNums() { let sum = 0 for (let i = 0; i < arguments.length; i++) { sum += arguments[i] } return sum } console.log(sumAllNums(1, 2, 3, 4)) // 10 console.log(sumAllNums(10, 20, 13, 40, 10)) // 93 console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173 ``` ##### Unlimited number of parameters in arrow function Arrow function does not have the function scoped arguments object. To implement a function which takes unlimited number of arguments in an arrow function we use spread operator followed by any parameter name. Any thing we passed as argument in the function can be accessed as array in the arrow function. Let us see an example ```js // Let us access the arguments object ​ const sumAllNums = (...args) => { // console.log(arguments), arguments object not found in arrow function // instead we use an a parameter followed by spread operator console.log(args) } sumAllNums(1, 2, 3, 4)) // [1, 2, 3, 4] ``` ```js // function declaration ​ const sumAllNums = (...args) => { let sum = 0 for (const element of args) { sum += element } return sum } console.log(sumAllNums(1, 2, 3, 4)) // 10 console.log(sumAllNums(10, 20, 13, 40, 10)) // 93 console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173 ``` #### Anonymous Function Anonymous function or without name ```js const anonymousFun = function () { console.log( 'I am an anonymous function and my value is stored in anonymousFun' ) } ``` #### Expression Function Expression functions are anonymous functions. After we create a function without a name and we assign it to a variable. To return a value from the function we should call the variable. Look at the example below. ```js // Function expression const square = function (n) { return n * n } console.log(square(2)) // -> 4 ``` #### Self Invoking Functions Self invoking functions are anonymous functions which do not need to be called to return a value. ```js ;(function (n) { console.log(n * n) })(2) // 4, but instead of just printing if we want to return and store the data, we do as shown below let squaredNum = (function (n) { return n * n })(10) console.log(squaredNum) ``` #### Arrow Function Arrow function is an alternative to write a function, however function declaration and arrow function have some minor differences. Arrow function uses arrow instead of the keyword _function_ to declare a function. Let us see both function declaration and arrow function. ```js // This is how we write normal or declaration function // Let us change this declaration function to an arrow function function square(n) { return n * n } console.log(square(2)) // 4 const square = (n) => { return n * n } console.log(square(2)) // -> 4 // if we have only one line in the code block, it can be written as follows, explicit return const square = (n) => n * n // -> 4 ``` ```js const changeToUpperCase = (arr) => { const newArr = [] for (const element of arr) { newArr.push(element.toUpperCase()) } return newArr } const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] console.log(changeToUpperCase(countries)) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] ``` ```js const printFullName = (firstName, lastName) => { return `${firstName} ${lastName}` } console.log(printFullName('Asabeneh', 'Yetayeh')) ``` The above function has only the return statement, therefore, we can explicitly return it as follows. ```js const printFullName = (firstName, lastName) => `${firstName} ${lastName}` console.log(printFullName('Asabeneh', 'Yetayeh')) ``` #### Function with default parameters Sometimes we pass default values to parameters, when we invoke the function if we do not pass an argument the default value will be used. Both function declaration and arrow function can have a default value or values. ```js // syntax // Declaring a function function functionName(param = value) { //codes } // Calling function functionName() functionName(arg) ``` **Example:** ```js function greetings(name = 'Peter') { let message = `${name}, welcome to 30 Days Of JavaScript!` return message } console.log(greetings()) console.log(greetings('Asabeneh')) ``` ```js function generateFullName(firstName = 'Asabeneh', lastName = 'Yetayeh') { let space = ' ' let fullName = firstName + space + lastName return fullName } console.log(generateFullName()) console.log(generateFullName('David', 'Smith')) ``` ```js function calculateAge(birthYear, currentYear = 2019) { let age = currentYear - birthYear return age } console.log('Age: ', calculateAge(1819)) ``` ```js function weightOfObject(mass, gravity = 9.81) { let weight = mass * gravity + ' N' // the value has to be changed to string first return weight } console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 gravity at the surface of Earth console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gravity at surface of Moon ``` Let us see how we write the above functions with arrow functions ```js // syntax // Declaring a function const functionName = (param = value) => { //codes } // Calling function functionName() functionName(arg) ``` **Example:** ```js const greetings = (name = 'Peter') => { let message = name + ', welcome to 30 Days Of JavaScript!' return message } console.log(greetings()) console.log(greetings('Asabeneh')) ``` ```js const generateFullName = (firstName = 'Asabeneh', lastName = 'Yetayeh') => { let space = ' ' let fullName = firstName + space + lastName return fullName } console.log(generateFullName()) console.log(generateFullName('David', 'Smith')) ``` ```js const calculateAge = (birthYear, currentYear = 2019) => currentYear - birthYear console.log('Age: ', calculateAge(1819)) ``` ```js const weightOfObject = (mass, gravity = 9.81) => mass * gravity + ' N' console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 gravity at the surface of Earth console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gravity at surface of Moon ``` #### Function declaration versus Arrow function It ill be covered in other time ### 💻 Exercises ##### Exercises: Level 1 1. Declare a function _fullName_ and it takes firstName, lastName as a parameter and it returns your full - name. 2. Declare a function _addNumbers_ and it takes two two parameters and it returns sum. 3. Area of a circle is calculated as follows: _area = π x r x r_. Write a function which calculates \_areaOfCircle 4. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelciusToFahrenheit_. 5. Body mass index(BMI) is calculated as follows: _bmi = weight in Kg / (height x height) in m2_. Write a function which calculates _bmi_. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is _underweight, normal, overweight_ or _obese_ based the information given below. - The same groups apply to both men and women. - _Underweight_: BMI is less than 18.5 - _Normal weight_: BMI is 18.5 to 24.9 - _Overweight_: BMI is 25 to 29.9 - _Obese_: BMI is 30 or more 6. Write a function called _checkSeason_, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer. ##### Exercises: Level 2 1. Quadratic equation is calculated as follows: _ax2 + bx + c = 0_. Write a function which calculates value or values of a quadratic equation, _solveQuadEquation_. ```js console.log(solveQuadratic()) // {0} console.log(solveQuadratic(1, 4, 4)) // {-2} console.log(solveQuadratic(1, -1, -2)) // {2, -1} console.log(solveQuadratic(1, 7, 12)) // {-3, -4} console.log(solveQuadratic(1, 0, -4)) //{2, -2} console.log(solveQuadratic(1, -1, 0)) //{1, 0} ``` 2. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array. 3. Write a function name _showDateTime_ which shows time in this format: 08/01/2020 04:08 using the Date object. ```sh showDateTime() 08/01/2020 04:08 ``` 4. Declare a function name _swapValues_. This function swaps value of x to y. ```js swapValues(3, 4) // x => 4, y=>3 swapValues(4, 5) // x = 5, y = 4 ``` 5. Declare a function name _reverseArray_. It takes array as a parameter and it returns the reverse of the array (don't use method). ```js console.log(reverseArray([1, 2, 3, 4, 5])) //[5, 4, 3, 2, 1] console.log(reverseArray(['A', 'B', 'C'])) //['C', 'B', 'A'] ``` 6. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray. 7. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item 8. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an ite 9. Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number. ```sh evensAndOdds(100); The number of odds are 50. The number of evens are 51. ``` 13. Write a function which takes any number of arguments and return the sum of the arguments ```js sum(1, 2, 3) // -> 6 sum(1, 2, 3, 4) // -> 10 ``` 1. Declare a function name _userIdGenerator_. When this function is called it generates seven character id. The function return the id. ```sh console.log(userIdGenerator()); 41XTDbE ``` ##### Exercises: Level 3 1. Declare a function name _userIdGeneratedByUser_. It doesn’t take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated. ```sh userIdGeneratedByUser() 'kcsy2 SMFYb bWmeq ZXOYh 2Rgxf ' userIdGeneratedByUser() '1GCSgPLMaBAVQZ26 YD7eFwNQKNs7qXaT ycArC5yrRupyG00S UbGxOFI7UXSWAyKN dIV0SSUTgAdKwStr ' ``` 2. Write a function **_generateColors_** which can generate any number of hexa or rgb colors. ```js console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b'] console.log(generateColors('hexa', 1)) // '#b334ef' console.log(generateColors('rgb', 3)) // ['rgb(5, 55, 175)', 'rgb(50, 105, 100)', 'rgb(15, 26, 80)'] console.log(generateColors('rgb', 1)) // 'rgb(33,79, 176)' ``` 3. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array 4. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number 5. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not 6. Write a function called _average_, it takes an array parameter and returns the average of the items. Check if all the array items are number types. If not give return reasonable feedback. ### 9. Higher Order Function Higher order functions are functions which take other function as a parameter or return a function as a value. The function passed as a parameter is called callback. #### Callback A callback is a function which can be passed as parameter to other function. See the example below. ```js // a callback function, the function could be any name const callback = (n) => { return n ** 2 } ​ // function take other function as a callback function cube(callback, n) { return callback(n) * n } ​ console.log(cube(callback, 3)) ``` #### Returning function Higher order functions return function as a value ​ ```js // Higher order function returning an other function const higherOrder = n => { const doSomething = m => { const doWhatEver = t => { return 2 * n + 3 * m + t } return doWhatEver } ​ return doSomething } console.log(higherOrder(2)(3)(10)) ``` Let us see were we use call back functions.For instance the _forEach_ method uses call back. ```js const numbers = [1, 2, 3, 4] const sumArray = arr => { let sum = 0 const callback = function(element) { sum += element } arr.forEach(callback) return sum } console.log(sumArray(numbers)) ``` ```sh 10 ``` The above example can be simplified as follows: ```js const numbers = [1, 2, 3, 4] ​ const sumArray = arr => { let sum = 0 arr.forEach(function(element) { sum += element }) return sum } console.log(sumArray(numbers)) ``` ```sh 10 ``` #### setting time In JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities. - setInterval - setTimeout ##### setInterval In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time. ```js // syntax function callback() { // code goes here } setInterval(callback, duration) ``` ```js function sayHello() { console.log('Hello') } setInterval(sayHello, 2000) // it prints hello in every 2 seconds ``` ##### setTimeout In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time. ```js // syntax function callback() { // code goes here } setTimeout(callback, duration) // duration in milliseconds ``` ```js function sayHello() { console.log('Hello') } setTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds. ``` ### 10. Destructuring and Spreading #### What is Destructuring? Destructuring is a way to unpack arrays, and objects and assigning to a distinct variable. Destructuring allows us to write clean and readable code. #### What can we destructure? 1. Arrays 2. Objects ##### 1. Destructuring arrays Arrays are a list of different data types ordered by their index. Let's see an example of arrays: ```js const numbers = [1, 2, 3] const countries = ['Finland', 'Sweden', 'Norway'] ``` We can access an item from an array using a certain index by iterating through the loop or manually as shown in the example below. Accessing array items using a loop ```js for (const number of numbers) { console.log(number) } for (const country of countries) { console.log(country) } ``` Accessing array items manually ```js const numbers = [1, 2, 3] let num1 = numbers[0] let num2 = numbers[1] let num3 = numbers[2] console.log(num1, num2, num3) // 1, 2, 3 const countries = ['Finland', 'Sweden', 'Norway'] let fin = countries[0] let swe = countries[1] let nor = countries[2] console.log(fin, swe, nor) // Finland, Sweden, Norway ``` Most of the time the size of an array is big and we use a loop to iterate through each item of the arrays. Sometimes, we may have short arrays. If the array size is very short it is ok to access the items manually as shown above but today we will see a better way to access the array item which is destructuring. Accessing array items using destructuring ```js const numbers = [1, 2, 3] const [num1, num2, num3] = numbers console.log(num1, num2, num3) // 1, 2, 3, const constants = [2.72, 3.14, 9.81,37, 100] const [e, pi, gravity, bodyTemp, boilingTemp] = constants console.log(e, pi, gravity, bodyTemp, boilingTemp] // 2.72, 3.14, 9.81, 37,100 const countries = ['Finland', 'Sweden', 'Norway'] const [fin, swe, nor] = countries console.log(fin, swe, nor) // Finland, Sweden, Norway ``` During destructuring each variable should match with the index of the desired item in the array. For instance, the variable fin matches to index 0 and the variable nor matches to index 2. What would be the value of den if you have a variable den next nor? ```js const [fin, swe, nor, den] = countries console.log(den) // undefined ``` If you tried the above task you confirmed that the value is undefined. Actually, we can pass a default value to the variable, and if the value of that specific index is undefined the default value will be used. ```js const countries = ['Finland', 'Sweden', undefined, 'Norway'] const [fin, swe, ice = 'Iceland', nor, den = 'Denmark'] = countries console.log(fin, swe, ice, nor, den) // Finland, Sweden, Iceland, Norway, Denmark ``` Destructuring Nested arrays ```js const fullStack = [ ['HTML', 'CSS', 'JS', 'React'], ['Node', 'Express', 'MongoDB'] ] const [frontEnd, backEnd] = fullstack console.log(frontEnd, backEnd) //["HTML", "CSS", "JS", "React"] , ["Node", "Express", "MongoDB"] const fruitsAndVegetables = [['banana', 'orange', 'mango', 'lemon'], ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']] const [fruits, vegetables] = fruitsAndVegetables console.log(fruits, vegetables] //['banana', 'orange', 'mango', 'lemon'] //['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] ``` Skipping an Item during destructuring During destructuring if we are not interested in every item, we can omit a certain item by putting a comma at that index. Let's get only Finland, Iceland, and Denmark from the array. See the example below for more clarity: ```js const countries = ['Finland', 'Sweden', 'Iceland', 'Norway', 'Denmark'] const [fin, , ice, , den] = countries console.log(fin, ice, den) // Finland, Iceland, Denmark ``` Getting the rest of the array using the spread operator We use three dots(...) to spread or get the rest of an array during destructuring ```js const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const [num1, num2, num3, ...rest] = nums console.log(num1, num2, num3, rest) //1, 2, 3, [4, 5, 6, 7, 8, 9, 10] const countries = [ 'Germany', 'France', 'Belgium', 'Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland', ] let [gem, fra, , ...nordicCountries] = countries console.log(gem, fra, nordicCountries) // Germany, France, ["Finland", "Sweden", "Norway", "Denmark", "Iceland"] ``` There many cases in which we use array destructuring, let's see the following example: Destructuring when we loop through arrays ```js const countries = [ ['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo'], ] for (const [country, city] of countries) { console.log(country, city) } const fullStack = [ ['HTML', 'CSS', 'JS', 'React'], ['Node', 'Express', 'MongoDB'], ] for (const [first, second, third, fourth] of fullStack) { console.log(first, second, third, fourt) } ``` What do you think about the code snippet below? If you have started React Hooks already it may remind you of the useState hook. ```js const [x, y] = [2, (value) => value ** 2] ``` What is the value of x? And what is the value of y(x)? I leave this for you to figure out. If you have used react hooks you are very familiar with this and as you may imagine it is destructuring. The initial value of count is 0 and the setCount is a method that changes the value of count. ```js const [count, setCount] = useState(0) ``` Now, you know how to destructure arrays. Let's move on to destructuring objects. ##### 2. Destructuring objects An object literal is made of key and value pairs. A very simple example of an object: ```js const rectangle = { width: 20, height: 10, } ``` We access the value of an object using the following methods: ```js const rectangle = { width: 20, height: 10, } let width = rectangle.width let height = recangle.height // or let width = rectangle[width] let height = recangle[height] ``` But today, we will see how to access the value of an object using destructuring. When we destructure an object the name of the variable should be exactly the same as the key or property of the object. See the example below. ```js const rectangle = { width: 20, height: 10, } let { width, height } = rectangle console.log(width, height, perimeter) // 20, 10 ``` What will be the value of we try to access a key which not in the object. ```js const rectangle = { width: 20, height: 10, } let { width, height, perimeter } = rectangleconsole.log( width, height, perimeter ) // 20, 10, undefined ``` The value of the perimeter in the above example is undefined. Default value during object destructuring Similar to the array, we can also use a default value in object destructuring. ```js const rectangle = { width: 20, height: 10, } let { width, height, perimeter = 200 } = rectangle console.log(width, height, perimeter) // 20, 10, undefined ``` Renaming variable names ```js const rectangle = { width: 20, height: 10, } let { width: w, height: h } = rectangle ``` Let's also destructure, nested objects. In the example below, we have nested objects and we can destructure it in two ways. We can just destructure step by step ```js const props = { user:{ firstName:'Asabeneh', lastName:'Yetayeh', age:250 }, post:{ title:'Destructuring and Spread', subtitle:'ES6', year:2020 }, skills:['JS', 'React', 'Redux', 'Node', 'Python'] } } const {user, post, skills} = props const {firstName, lastName, age} = user const {title, subtitle, year} = post const [skillOne, skillTwo, skillThree, skillFour, skillFive] = skills ``` 1. We can destructure it one step ```js const props = { user:{ firstName:'Asabeneh', lastName:'Yetayeh', age:250 }, post:{ title:'Destructuring and Spread', subtitle:'ES6', year:2020 }, skills:['JS', 'React', 'Redux', 'Node', 'Python'] } } const {user:{firstName, lastName, age}, post:{title, subtitle, year}, skills:[skillOne, skillTwo, skillThree, skillFour, skillFive]} = props ``` Destructuring during loop through an array ```js const languages = [ { lang: 'English', count: 91 }, { lang: 'French', count: 45 }, { lang: 'Arabic', count: 25 }, { lang: 'Spanish', count: 24 }, { lang: 'Russian', count: 9 }, { lang: 'Portuguese', count: 9 }, { lang: 'Dutch', count: 8 }, { lang: 'German', count: 7 }, { lang: 'Chinese', count: 5 }, { lang: 'Swahili', count: 4 }, { lang: 'Serbian', count: 4 }, ] for (const { lang, count } of languages) { console.log(`The ${lang} is spoken in ${count} countries.`) } ``` Destructuring function parameter ```js const rectangle = { width: 20, height: 10 } const calcualteArea = ({ width, height }) => width * height const calculatePerimeter = ({ width, height } = 2 * (width + height)) ``` #### Exercises Create a function called getPersonInfo. The getPersonInfo function takes an object parameter. The structure of the object and the output of the function is given below. Try to use both a regular way and destructuring and compare the cleanness of the code. If you want to compare your solution with my solution, check this link. ```js const person = { firstName: 'Asabeneh', lastName: 'Yetayeh', age: 250, country: 'Finland', job: 'Instructor and Developer', skills: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node', 'MongoDB', 'Python', 'D3.js', ], languages: ['Amharic', 'English', 'Suomi(Finnish)'], } /* Asabeneh Yetayeh lives in Finland. He is 250 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish) */ ``` #### Spread or Rest Operator When we destructure an array we use the spread operator(...) to get the rest elements as array. In addition to that we use spread operator to spread arr elements to another array. ##### Spread operator to get the rest of array elements ```js const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let [num1, num2, num3, ...rest] = nums ​ console.log(num1, num2, num3) console.log(rest) ``` ```sh 1 2 3 [4, 5, 6, 7, 8, 9, 10] ``` ```js const countries = [ 'Germany', 'France', 'Belgium', 'Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland', ] let [gem, fra, , ...nordicCountries] = countries console.log(gem) console.log(fra) console.log(nordicCountries) ``` ```sh Germany France ["Finland", "Sweden", "Norway", "Denmark", "Iceland"] ``` ##### Spread operator to copy array ```js const evens = [0, 2, 4, 6, 8, 10] const evenNumbers = [...evens] const odds = [1, 3, 5, 7, 9] const oddNumbers = [...odds] const wholeNumbers = [...evens, ...odds] console.log(evenNumbers) console.log(oddNumbers) console.log(wholeNumbers) ``` ```sh [0, 2, 4, 6, 8, 10] [1, 3, 5, 7, 9] [0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9] ``` ```js const frontEnd = ['HTML', 'CSS', 'JS', 'React'] const backEnd = ['Node', 'Express', 'MongoDB'] const fullStack = [...frontEnd, ...backEnd] console.log(fullStack) ``` ```sh ["HTML", "CSS", "JS", "React", "Node", "Express", "MongoDB"] ``` ##### Spread operator to copy object We can copy an object using a spread operator ```js const user = { name: 'Asabeneh', title: 'Programmer', country: 'Finland', city: 'Helsinki', } const copiedUser = { ...user } console.log(copiedUser) ``` ```sh {name: "Asabeneh", title: "Programmer", country: "Finland", city: "Helsinki"} ``` Modifying or changing the object while copying ```js const user = { name: 'Asabeneh', title: 'Programmer', country: 'Finland', city: 'Helsinki', } const copiedUser = { ...user, title: 'instructor' } console.log(copiedUser) ``` ```sh {name: "Asabeneh", title: "instructor", country: "Finland", city: "Helsinki"} ``` ##### Spread operator with arrow function Whenever we like to write an arrow function which takes unlimited number of arguments we use a spread operator. If we use a spread operator as a parameter, the argument passed when we invoke a function will change to an array. ```js const sumAllNums = (...args) => { console.log(args) } sumAllNums(1, 2, 3, 4, 5) ``` ```sh [1, 2, 3, 4, 5] ``` ```js const sumAllNums = (...args) => { let sum = 0 for (const num of args) { sum += num } return sum } console.log(sumAllNums(1, 2, 3, 4, 5)) ``` ```sh 15 ``` ### 11. Functional Programming In this article, I will try to help you to have a very good understanding of the most common feature of JavaScript, _functional programming_. _Functional programming_ allows you to write shorter code, clean code, and also to solve complicated problems which might be difficult to solve in a traditional way. In this article we will cover all JS functional programming methods: - forEach - map - filter - reduce - find - findIndex - some - every #### 1. forEach We use forEach when we like to iterate through an array of items. The forEach is a higher-order function and it takes call-back as a parameter. The forEach method is used only with array and we use forEach if you are interested in each item or index or both. ```js // syntax in a normal or a function declaration function callback(item, index, arr) {} array.forEach(callback) // or syntax in an arrow function const callback = (item, i, arr) => {} array.forEach(callback) ``` The call back function could be a function declaration or an arrow function. Let see different examples ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway'] countries.forEach(function (country, index, arr) { console.log(i, country.toUpperCase()) }) ``` If there is no much code inside the code block we can use an arrow function and we can write it without a curly bracket. The index and the array parameters are optional, we can omit them. ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway'] countries.forEach((country, i) => console.log(i, country.toUpperCase())) ``` ```sh 0 "FINLAND" 1 "ESTONIA" 2 "SWEDEN" 3 "NORWAY" ``` For example if we like to change each country to uppercase and store it back to an array we write it as follows. ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway'] const newCountries = [] countries.forEach((country) => newCountries.push(country)) console.log(newCountries) // ["Finland", "Estonia", "Sweden", "Norway"] ``` Let us see more examples. For instance if we want to sum an array of numbers we can use forEach or reduce. Let us see how we use forEach to sum all numbers in an array. ```js const numbers = [1, 2, 3, 4, 5] let sum = 0 numbers.forEach((n) => (sum += n)) console.log(sum) // 15 ``` Let us move to the next functional programming method which is going to be a map. #### 2. map We use the map method whenever we like to modify an array. We use the map method only with arrays and it always returns an array. ```js // syntax in a normal or a function declaration function callback(item, i) { return // code goes here } const modifiedArray = array.map(callback) // or syntax in an arrow function const callback = (item, i) => { return // code goes here } const modifiedArray = array.map(callback) ``` Now, let us modify the countries array using the map method. The index is an optional parameter ```js // Using function declaration const countries = ['Finland', 'Estonia', 'Sweden', 'Norway'] const newCountries = countries.map(function (country) { return country.toUpperCase() }) console.log(newCountries) // map using an arrow function call back const countries = ['Finland', 'Estonia', 'Sweden', 'Norway'] const newCountries = countries.map((country) => country.toUpperCase()) console.log(newCountries) // ["FINLAND", "ESTONIA", "SWEDEN", "NORWAY"] ``` As you can see that map is very handy to modify an array and to get an array back. Now, let us create an array of the length of the countries from the countries array. ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway'] const countriesLength = countries.map((country) => country.length) console.log(countriesLength) // [7, 7, 6, 6] ``` Let us see another more example ```js const numbers = [1, 2, 3, 4, 5] const squares = numbers.map((n) => n ** 2) console.log(squares) // [1, 4, 9, 16, 25] ``` #### 3. filter As you may understand from the literal meaning of filter, it filters out items based on some criteria. The filter method like forEach and map is used with an array and it returns an array of the filtered items. For instance if we want to filter out countries containing a substring land from an array of countries. See the example below: ```js // syntax in a normal or a function declaration function callback(item) { return // boolean } const filteredArray = array.filter(callback) // or syntax in an arrow function const callback = (item) => { return // boolean } const filteredArray = array.filter(callback) ``` ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland'] const countriesWithLand = countries.filter((country) => country.includes('land') ) console.log(countriesWithLand) // ["Finland", "Iceland"] ``` How about if we want to filter out countries not containing the substring land. We use negation to achieve that. ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland'] const countriesWithLand = countries.filter( (country) => !country.includes('land') ) console.log(countriesWithLand) // ["Estonia", "Sweden", "Norway"] ``` Let's see an additional example about the filter, let us filter even or odd numbers from an array of numbers ```js const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const evens = numbers.filter((n) => n % 2 === 0) const odds = numbers.filter((n) => n % 2 !== 0) console.log(evens) // [0, 2, 4, 6, 8, 10] console.log(odds) // [1, 3, 5, 7, 9] ``` Now, you know how to filter let us move on to the next functional programming, reduce. #### 4. reduce Like forEach, map, and filter, reduce is also used with an array and it returns a single value. You can associate reduce with a blender. You put different fruits to a blend and you get a mix of fruit juice. The juice is the output from the reduction process. We use the reduce method to sum all numbers in an array together, or to multiply items in an array or to concatenate items in an array. Let us see the following different example to make this explanation more clear. ```js // syntax in a normal or a function declaration function callback(acc, cur) { return // code goes here } const reduced = array.reduce(callback, optionalInitialValue) // or syntax in an arrow function const reduced = callback(acc, cur) => { return // code goes here } const reduced = array.reduce(callback) ``` The default initial value is 0. We can change the initial value if we want to change it. For instance if we want to add all items in an array and if all the items are numbers we can use reduce. ```js const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const sum = numbers.reduce((acc, cur) => acc + cur) console.log(sum) // 55 ``` Reduce has a default initial value which is zero. Now, let us use a different initial value which is 5 in this case. ```js const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const sum = numbers.reduce((acc, cur) => acc + cur, 5) console.log(sum) // 60 ``` Let us concatenate strings using reduce ```js const strs = ['Hello', 'world', '!'] const helloWorld = strs.reduce((acc, cur) => acc + ' ' + cur) console.log(helloWorld) // "Hello world !" ``` We can multiply items of an array using reduce and we will return the value. ```js const numbers = [1, 2, 3, 4, 5] const value = numbers.reduce((acc, cur) => acc * cur) console.log(value) // 120 ``` Let us try it with an initial value ```js const numbers = [1, 2, 3, 4, 5] const value = numbers.reduce((acc, cur) => acc * cur, 10) console.log(value) // 1200 ``` #### 5. find If we are interested in the first occurrence of a certain item or element in an array we can use find method. Unlike map and filter, find just return the first occurrence of an item instead of an array. ```js // syntax in a normal or a function declaration function callback(item) { return // code goes here } const item = array.find(callback) // or syntax in an arrow function const reduced = callback(item) => { return // code goes here } const item = array.find(callback) ``` Let find the first even number and the first odd number in the numbers array. ```js const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const firstEvenNum = numbers.find((n) => n % 2 === 0) const firstOddNum = numbers.find((n) => n % 2 !== 0) console.log(firstEvenNum) // 0 console.log(firstOddNum) // 1 ``` Let us find the first country which contains a substring way ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland'] const countryWithWay = countries.find((country) => country.includes('way')) console.log(countriesWithWay) // Norway ``` Let us find the first country which has only six characters ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland'] const sixCharsCountry = countries.find((country) => country.length === 6) console.log(sixCharsCountry) // Sweden ``` Let us find the first country in the array which has the letter 'o' ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland'] const index = countries.find((country) => country.includes('o')) console.log(index // Estonia ``` #### 6. findIndex The findIndex method works like find but findIndex returns the index of the item. If we are interested in the index of a certain item or element in an array we can use findIndex. The findIndex return the index of the first occurrence of an item. ```js // syntax in a normal or a function declaration function callback(item) { return // code goes here } const index = array.findIndex(callback) // or syntax in an arrow function const reduced = callback(item) => { return // code goes here } const index = array.findIndex(callback) ``` Let us find the index of the first even number and the index of the first odd number in the numbers array. ```js const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const firstEvenIndex = numbers.findIndex((n) => n % 2 === 0) const firstOddIndex = numbers.findIndex((n) => n % 2 !== 0) console.log(firstEvenIndex) // 0 console.log(firstOddIndex) // 1 ``` Let us find the index of the first country in the array which has exactly six characters ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland'] const index = countries.findIndex((country) => country.length === 6) console.log(index //2 ``` Let us find the index of the first country in the array which has the letter 'o'. ```js const countries = ['Finland', 'Estonia', 'Sweden', 'Norway', 'Iceland'] const index = countries.findIndex((country) => country.includes('o')) console.log(index // 1 ``` Let us move on to the next functional programming, some. #### 7. some The some method is used with array and return a boolean. If one or some of the items satisfy the criteria the result will be true else it will be false. Let us see it with an example. In the following array some numbers are even and some are odd, so if I ask you a question, are there even numbers in the array then your answer will be yes. If I ask you also another question, are there odd numbers in the array then your answer will be yes. On the contrary, if I ask you, are all the numbers even or odd then your answer will be no because all the numbers are not even or odd. ```js const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const someAreEvens = numbers.some((n) => n % 2 === 0) const someAreOdds = numbers.some((n) => n % 2 !== 0) console.log(someAreEvens) // true console.log(someAreOdds) // true ``` Let us another example ```js const evens = [0, 2, 4, 6, 8, 10] const someAreEvens = evens.some((n) => n % 2 === 0) const someAreOdds = evens.some((n) => n % 2 !== 0) console.log(someAreEvens) // true console.log(someAreOdds) // false ``` Now, let us see one more functional programming, every. #### 8. every The method every is somehow similar to some but every item must satisfy the criteria. The method every like some returns a boolean. ```js const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const allAreEvens = numbers.every((n) => n % 2 === 0) const allAreOdd s= numbers.every((n) => n % 2 !== 0) console.log(allAreEven) // false console.log(allAreOdd) // false const evens = [0, 2, 4, 6, 8, 10] const someAreEvens = evens.some((n) => n % 2 === 0) const someAreOdds = evens.some((n) => n % 2 !== 0) console.log(someAreEvens) // true console.log(someAreOdds) // false ``` #### Exercises ```js const products = [ { product: 'banana', price: 3 }, { product: 'mango', price: 6 }, { product: 'potato', price: ' ' }, { product: 'avocado', price: 8 }, { product: 'coffee', price: 10 }, { product: 'tea', price: '' }, ] ``` 1. Print the price of each product using forEach 2. Print the product items as follows using forEach ```sh The price of banana is 3 euros. The price of mango is 6 euros. The price of potato is unknown. The price of avocado is 8 euros. The price of coffee is 10 euros. The price of tea is unknown. ``` 3. Calculate the sum of all the prices using forEach 4. Create an array of prices using map and store it in a variable prices 5. Filter products with prices 6. Use method chaining to get the sum of the prices(map, filter, reduce) 7. Calculate the sum of all the prices using reduce only 8. Find the first product which doesn't have a price value 9. Find the index of the first product which does not have price value 10. Check if some products do not have a price value 11. Check if all the products have price value 12. Explain the difference between forEach, map, filter and reduce 13. Explain the difference between filter, find and findIndex 14. Explain the difference between some and every ### 12. Classes JavaScript is an object oriented programming language. Everything in JavScript is an object, with its properties and methods. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class. Once we create a class we can create object from it whenever we want. Creating an object from a class is called class instantiation. In the object section, we saw how to create an object literal. Object literal is a singleton. If we want to get a similar object , we have to write it. However, class allows to create many objects. This helps to reduce amount of code and repetition of code. #### Defining a classes To define a class in JavaScript we need the keyword _class_ , the name of a class in **CamelCase** and block code(two curly brackets). Let us create a class name Person. ```sh // syntax class ClassName { // code goes here } ``` **Example:** ```js class Person { // code goes here } ``` We have created an Person class but it does not have any thing inside. #### Class Instantiation Instantiation class means creating an object from a class. We need the keyword _new_ and we call the name of the class after the word new. Let us create a dog object from our Person class. ```js class Person { // code goes here } const person = new Person() console.log(person) ``` ```sh Person {} ``` As you can see, we have created a person object. Since the class did not have any properties yet the object is also empty. Let use the class constructor to pass different properties for the class. #### Class Constructor The constructor is a builtin function which allows as to create a blueprint for our object. The constructor function starts with a keyword constructor followed by a parenthesis. Inside the parenthesis we pass the properties of the object as parameter. We use the _this_ keyword to attach the constructor parameters with the class. The following Person class constructor has firstName and lastName property. These properties are attached to the Person class using _this_ keyword. _This_ refers to the class itself. ```js class Person { constructor(firstName, lastName) { console.log(this) // Check the output from here this.firstName = firstName this.lastName = lastName } } const person = new Person() console.log(person) ``` ```sh Person {firstName: undefined, lastName} ``` All the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class. ```js class Person { constructor(firstName, lastName) { this.firstName = firstName this.lastName = lastName } } const person1 = new Person('Asabeneh', 'Yetayeh') console.log(person1) ``` ```sh Person {firstName: "Asabeneh", lastName: "Yetayeh"} ``` As we have stated at the very beginning that once we create a class we can create many object using the class. Now, let us create many person objects using the Person class. ```js class Person { constructor(firstName, lastName) { console.log(this) // Check the output from here this.firstName = firstName this.lastName = lastName } } const person1 = new Person('Asabeneh', 'Yetayeh') const person2 = new Person('Lidiya', 'Tekle') const person3 = new Person('Abraham', 'Yetayeh') console.log(person1) console.log(person2) console.log(person3) ``` ```sh Person {firstName: "Asabeneh", lastName: "Yetayeh"} Person {firstName: "Lidiya", lastName: "Tekle"} Person {firstName: "Abraham", lastName: "Yetayeh"} ``` Using the class Person we created three persons object. As you can see our class did not many properties let us add more properties to the class. ```js class Person { constructor(firstName, lastName, age, country, city) { console.log(this) // Check the output from here this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city } } const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') console.log(person1) ``` ```sh Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"} ``` #### Default values with constructor The constructor function properties may have a default value like other regular functions. ```js class Person { constructor( firstName = 'Asabeneh', lastName = 'Yetayeh', age = 250, country = 'Finland', city = 'Helsinki' ) { this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city } } const person1 = new Person() // it will take the default values const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo') console.log(person1) console.log(person2) ``` ```sh Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"} Person {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Espoo"} ``` #### Class methods The constructor inside a class is a builtin function which allow us to create a blueprint for the object. In a class we can create class methods. Methods are JavaScript functions inside the class. Let us create some class methods. ```js class Person { constructor(firstName, lastName, age, country, city) { this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city } getFullName() { const fullName = this.firstName + ' ' + this.lastName return fullName } } const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo') console.log(person1.getFullName()) console.log(person2.getFullName()) ``` ```sh Asabeneh Yetayeh test.js:19 Lidiya Tekle ``` #### Properties with initial value When we create a class for some properties we may have an initial value. For instance if you are playing a game, you starting score will be zero. So, we may have a starting score or score which is zero. In other way, we may have an initial skill and we will acquire some skill after some time. ```js class Person { constructor(firstName, lastName, age, country, city) { this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city this.score = 0 this.skills = [] } getFullName() { const fullName = this.firstName + ' ' + this.lastName return fullName } } const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo') console.log(person1.score) console.log(person2.score) console.log(person1.skills) console.log(person2.skills) ``` ```sh 0 0 [] [] ``` A method could be regular method or a getter or a setter. Let us see, getter and setter. #### getter The get method allow us to access value from the object. We write a get method using keyword _get_ followed by a function. Instead of accessing properties directly from the object we use getter to get the value. See the example bellow ```js class Person { constructor(firstName, lastName, age, country, city) { this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city this.score = 0 this.skills = [] } getFullName() { const fullName = this.firstName + ' ' + this.lastName return fullName } get getScore() { return this.score } get getSkills() { return this.skills } } const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo') console.log(person1.getScore) // We do not need parenthesis to call a getter method console.log(person2.getScore) console.log(person1.getSkills) console.log(person2.getSkills) ``` ```sh 0 0 [] [] ``` #### setter The setter method allow us to modify the value of certain properties. We write a setter method using keyword _set_ followed by a function. See the example bellow. ```js class Person { constructor(firstName, lastName, age, country, city) { this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city this.score = 0 this.skills = [] } getFullName() { const fullName = this.firstName + ' ' + this.lastName return fullName } get getScore() { return this.score } get getSkills() { return this.skills } set setScore(score) { this.score += score } set setSkill(skill) { this.skills.push(skill) } } const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo') person1.setScore = 1 person1.setSkill = 'HTML' person1.setSkill = 'CSS' person1.setSkill = 'JavaScript' person2.setScore = 1 person2.setSkill = 'Planning' person2.setSkill = 'Managing' person2.setSkill = 'Organizing' console.log(person1.score) console.log(person2.score) console.log(person1.skills) console.log(person2.skills) ``` ```sh 1 1 ["HTML", "CSS", "JavaScript"] ["Planning", "Managing", "Organizing"] ``` Do not be puzzled by the difference between regular method and a getter. If you know how to make a regular method you are good. Let us add regular method called getPersonInfo in the Person class. ```js class Person { constructor(firstName, lastName, age, country, city) { this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city this.score = 0 this.skills = [] } getFullName() { const fullName = this.firstName + ' ' + this.lastName return fullName } get getScore() { return this.score } get getSkills() { return this.skills } set setScore(score) { this.score += score } set setSkill(skill) { this.skills.push(skill) } getPersonInfo() { let fullName = this.getFullName() let skills = this.skills.length > 0 && this.skills.slice(0, this.skills.length - 1).join(', ') + ` and ${this.skills[this.skills.length - 1]}` let formattedSkills = skills ? `He knows ${skills}` : '' let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}` return info } } const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo') const person3 = new Person('John', 'Doe', 50, 'Mars', 'Mars city') person1.setScore = 1 person1.setSkill = 'HTML' person1.setSkill = 'CSS' person1.setSkill = 'JavaScript' person2.setScore = 1 person2.setSkill = 'Planning' person2.setSkill = 'Managing' person2.setSkill = 'Organizing' console.log(person1.getScore) console.log(person2.getScore) console.log(person1.getSkills) console.log(person2.getSkills) console.log(person3.getSkills) console.log(person1.getPersonInfo()) console.log(person2.getPersonInfo()) console.log(person3.getPersonInfo()) ``` ```sh 1 1 ["HTML", "CSS", "JavaScript"] ["Planning", "Managing", "Organizing"] [] Asabeneh Yetayeh is 250. He lives Helsinki, Finland. He knows HTML, CSS and JavaScript Lidiya Tekle is 28. He lives Espoo, Finland. He knows Planning, Managing and Organizing John Doe is 50. He lives Mars city, Mars. ``` #### Static method The static keyword defines a static method for a class. Static methods are not called on instances of the class. Instead, they are called on the class itself. These are often utility functions, such as functions to create or clone objects. An example of static method is _Date.now()_. The _now_ method is called directly from the class. ```js class Person { constructor(firstName, lastName, age, country, city) { this.firstName = firstName this.lastName = lastName this.age = age this.country = country this.city = city this.score = 0 this.skills = [] } getFullName() { const fullName = this.firstName + ' ' + this.lastName return fullName } get getScore() { return this.score } get getSkills() { return this.skills } set setScore(score) { this.score += score } set setSkill(skill) { this.skills.push(skill) } getPersonInfo() { let fullName = this.getFullName() let skills = this.skills.length > 0 && this.skills.slice(0, this.skills.length - 1).join(', ') + ` and ${this.skills[this.skills.length - 1]}` let formattedSkills = skills ? `He knows ${skills}` : '' let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}` return info } static favoriteSkill() { const skills = ['HTML', 'CSS', 'JS', 'React', 'Python', 'Node'] const index = Math.floor(Math.random() * skills.length) return skills[index] } static showDateTime() { let now = new Date() let year = now.getFullYear() let month = now.getMonth() + 1 let date = now.getDate() let hours = now.getHours() let minutes = now.getMinutes() if (hours < 10) { hours = '0' + hours } if (minutes < 10) { minutes = '0' + minutes } let dateMonthYear = date + '.' + month + '.' + year let time = hours + ':' + minutes let fullTime = dateMonthYear + ' ' + time return fullTime } } console.log(Person.favoriteSkill()) console.log(Person.showDateTime()) ``` ```sh Node 15.1.2020 23:56 ``` The static methods are methods which can be used as utility functions. #### Inheritance Using inheritance we can access all the properties and the methods of the parent class. This reduces repetition of code. If you remember, we have a Person parent class and we will create children from it. Our children class could be student, teach etc. ```js // syntax class ChildClassName extends { // code goes here } ``` Let us create a Student child class from Person parent class. ```js class Student extends Person { saySomething() { console.log('I am a child of the person class') } } const s1 = new Student('Asabeneh', 'Yetayeh', 'Finland', 250, 'Helsinki') console.log(s1) console.log(s1.saySomething()) console.log(s1.getFullName()) console.log(s1.getPersonInfo()) ``` ```sh Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …} I am a child of the person class Asabeneh Yetayeh Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …} Asabeneh Yetayeh is Finland. He lives Helsinki, 250. ``` #### Overriding methods As you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. In side the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden. ```js class Student extends Person { constructor(firstName, lastName, age, country, city, gender) { super(firstName, lastName, age, country, city) this.gender = gender } saySomething() { console.log('I am a child of the person class') } getPersonInfo() { let fullName = this.getFullName() let skills = this.skills.length > 0 && this.skills.slice(0, this.skills.length - 1).join(', ') + ` and ${this.skills[this.skills.length - 1]}` let formattedSkills = skills ? `He knows ${skills}` : '' let pronoun = this.gender == 'Male' ? 'He' : 'She' let info = `${fullName} is ${this.age}. ${pronoun} lives in ${this.city}, ${this.country}. ${formattedSkills}` return info } } const s1 = new Student( 'Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki', 'Male' ) const s2 = new Student('Lidiya', 'Tekle', 28, 'Finland', 'Helsinki', 'Female') s1.setScore = 1 s1.setSkill = 'HTML' s1.setSkill = 'CSS' s1.setSkill = 'JavaScript' s2.setScore = 1 s2.setSkill = 'Planning' s2.setSkill = 'Managing' s2.setSkill = 'Organizing' console.log(s1) console.log(s1.saySomething()) console.log(s1.getFullName()) console.log(s1.getPersonInfo()) console.log(s2.saySomething()) console.log(s2.getFullName()) console.log(s2.getPersonInfo()) ``` ```sh Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …} Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …} I am a child of the person class Asabeneh Yetayeh Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …} Asabeneh Yetayeh is 250. He lives in Helsinki, Finland. He knows HTML, CSS and JavaScript I am a child of the person class Lidiya Tekle Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …} Lidiya Tekle is 28. She lives in Helsinki, Finland. He knows Planning, Managing and Organizing ``` Now, the getPersonInfo method has been overridden and it identifies if the person is male or female. #### Exercises ##### Exercises Level 1 1. Create an Animal class. The class will have name, age, color, legs properties and create different methods 2. Create a Dog and Cat child class from the Animal Class. ##### Exercises Level 2 1. Override the method you create in Animal class ##### Exercises Level 3 1. Let's try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create a class called Statistics and create all the functions which do statistical calculations as method for the Statistics class. Check the output below. ```JS ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26] console.log('Count:', statistics.count()) // 25 console.log('Sum: ', statistics.sum()) // 744 console.log('Min: ', statistics.min()) // 24 console.log('Max: ', statistics.max()) // 38 console.log('Range: ', statistics.range() // 14 console.log('Mean: ', statistics.mean()) // 30 console.log('Median: ',statistics.median()) // 29 console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5} console.log('Variance: ',statistics.var()) // 17.5 console.log('Standard Deviation: ', statistics.std()) // 4.2 console.log('Variance: ',statistics.var()) // 17.5 console.log('Frequency Distribution: ',statistics.freqDist()) // [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)] ``` ```sh // you output should look like this console.log(statistics.describe()) Count: 25 Sum: 744 Min: 24 Max: 38 Range: 14 Mean: 30 Median: 29 Mode: (26, 5) Variance: 17.5 Standard Deviation: 4.2 Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)] ``` ### 13 Document Object Model(DOM) HTML document is structured as a JavaScript Object. Every HTML element has a different properties which can help us to manipulate it. It is possible to get, create, append or remove HTML elements using JavaScript. When it comes to React we do not directly manipulate the DOM instead React Virtual DOM will take care of update all necessary changes. So do not directly manipulate the DOM if you are using react. The only place we directly touch the DOM is here at the index.html. React is a single page application because all the components will be rendered on the index.html page and there will not be any other HTML in the entire React Application. You don't have to know DOM very well to use react but recommended to know. ```html React App
``` Check out there result on [codepen](https://codepen.io/Asabeneh/full/vYGqQxP) 🌕 You are amazing! You have just completed day 1 challenge and you are on your way to greatness. Now you are a JavaScript Ninja and ready to dive into React. 🎉 CONGRATULATIONS ! 🎉 [<< Day 0](../readMe.md) | [Day 2 >>](../02_Day_Introduction_to_React/02_introduction_to_react.md) ================================================ FILE: 02_Day_Introduction_to_React/02_introduction_to_react.md ================================================

30 Days Of React: Getting Started React

Twitter Follow Author: Asabeneh Yetayeh
October, 2020
[<< Day 1](../01_Day_JavaScript_Refresher/01_javascript_refresher.md) | [Day 3 >>](../03_Day_Setting_Up/03_setting_up.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_2.jpg) - [Getting Started React](#getting-started-react) - [1. What is React?](#1-what-is-react) - [2. Why React?](#2-why-react) - [React vs Vue popularity in October 2020](#react-vs-vue-popularity-in-october-2020) - [React vs Vue popularity in February 2020](#react-vs-vue-popularity-in-february-2020) - [3. JSX](#3-jsx) - [JSX Element](#jsx-element) - [Commenting a JSX element](#commenting-a-jsx-element) - [Rendering a JSX Element](#rendering-a-jsx-element) - [Style and className in JSX](#style-and-classname-in-jsx) - [Injecting data to a JSX Element](#injecting-data-to-a-jsx-element) - [Injecting a string to a JSX Element](#injecting-a-string-to-a-jsx-element) - [Injecting a number to a JSX Element](#injecting-a-number-to-a-jsx-element) - [Injecting an array to a JSX Element](#injecting-an-array-to-a-jsx-element) - [Injecting an object to a JSX Element](#injecting-an-object-to-a-jsx-element) - [Exercises](#exercises) - [Exercises: What is React?](#exercises-what-is-react) - [Exercises: Why React?](#exercises-why-react) - [Exercises: JSX](#exercises-jsx) - [Exercises: JSX Elements](#exercises-jsx-elements) - [Exercises: Inline Style](#exercises-inline-style) - [Exercises: Internal Styles](#exercises-internal-styles) - [Exercise: Inject data to JSX](#exercise-inject-data-to-jsx) ## Getting Started React This section covers prerequisites to get started with React. You should have a good understanding of the following technologies: - HTML - CSS - JavaScript If you have the skills mentioned above, you will enjoy doing React. The 30 Days Of React challenge contains everything you need to know about react. In every section, it has some exercises and mini-projects, and it is recommended to work on them. This 30 Days Of React challenge will help you learn the latest version of React and the old version, step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples and many hands-on exercises. This challenge is designed for beginners and professionals who want to build a web application using React and JavaScript. Once in a while you may need different dummy data to work with React. You can use the following [dummy data generator](https://www.30daysofreact.com/dummy-data) to generate different data. ### 1. What is React? React is a JavaScript library for building a reusable user interface(UI). It was initially released on May 29, 2013. The current version is 16.13.1 and somehow it is stable. React was created by Facebook. React makes creating UI components very easy. The official React documentation can be found [here](https://reactjs.org/docs/getting-started.html). When we work with React we do not interact directly with the DOM. React has its own way to handle the DOM(Document Object Model) manipulation. React uses its virtual DOM to make new changes and it updates only the element, that needs changing. Do not directly interact with DOM when you build a React Application and leave the DOM manipulation job for the React virtual DOM. In this challenge, we will develop 10-15 web applications using React. A web application, or a website, is made of buttons, links, forms with different input fields, header, footer, sections, articles, texts, images, audios, videos and boxes with different shapes. We use react to make a reusable UI components of a website. To summarize: - React was released in May 2013 - React was created by Facebook - React is a JavaScript library for building user interfaces - React is used to build single page applications - An application which has only one HTML page. - React allows us to create reusable UI components - React latest release is 16.13.1 - [React versions](https://reactjs.org/versions/) - React official documentation can be found [here](https://reactjs.org/docs/getting-started.html) ### 2. Why React? React is one of the most popular JavaScript libraries. Many developers and companies have been using it for the last couple of years. Its popularity has been growing fast and it has a huge community. How do we measure popularity? One measure of popularity could be GitHub repository stars, watchers and forks. Let us compare the popularity of [React](https://github.com/facebook/react) and [Vue](https://github.com/vuejs/vue). As of today, the popularity between the two most popular JavaScript looks like as shown on the diagram. From the diagram, you can speculate the most popular JavaScript library. You may look at the number of watchers, stars and forks for both React and Vue. These alone will not be a very good measure of popularity, but still it tells a little bit about the popularity of the two technologies. If I have to recommend another JavaScript library next to React, it would be Vue.js. #### React vs Vue popularity in October 2020 React Official GitHub Repository ![React Popularity October 2020](../images/react_repo_1_oct_2020.png) Vue Official GitHub Repository ![Vue Popularity October 2020](../images/vue_repo_1_oct_2020.png) #### React vs Vue popularity in February 2020 React Official GitHub Repository ![React Popularity February 2020](../images/react_popularity.png) Vue Official GitHub Repository ![Vue Popularity February 2020](../images/vue_popularity.png) Why we choose to use React ? We use it because of the following reasons: - fast - modular - scalable - flexible - big community and popular - open source - High job opportunity ### 3. JSX JSX stands for JavaScript XML. JSX allows us to write HTML elements with JavaScript code. An HTML element has an opening and closing tags, content, and attribute in the opening tag. However, some HTML elements may not have content and a closing tag - they are self closing elements. To create HTML elements in React we do not use the _createElement()_ instead we just use JSX elements. Therefore, JSX makes it easier to write and add HTML elements in React. JSX will be converted to JavaScript on browser using a transpiler - [babel.js](https://babeljs.io/). Babel is a library which transpiles JSX to pure JavaScript and latest JavaScript to older version. See the JSX code below. ```js // JSX syntax // we don't need to use quotes with JSX const jsxElement =

I am a JSX element

const welcome =

Welcome to 30 Days of React Challenge

const data = Oct 2, 2020 ``` The above strange looking code seems like JavaScript and it seems like , but it is not JavaScript and it seems like HTML but not completely an HTML element. It is a mix of JavaScript and an HTML elements. JSX can allow us to use HTML in JavaScript. The HTML element in the JSX above is _h1_ and _small_. #### JSX Element As you have seen in the example above, JSX has a JavaScript and HTML like syntax. JSX element could be a single HTML element or many HTML elements wrapped in a parent HTML element. This JSX element has only one HTML element which is _h1_. ```js const jsxElement =

I am a JSX element

// JS with HTML ``` Let's make more JSX elements by declaring a new variable named title and content inside _h2_. ```js const title =

Getting Started React

``` Let us add a subtitles and other contents to this JSX element by adding additional HTML elements. Every HTML element should be wrapped by an outer HTML element to create a valid JSX element. The name title variable also should be changed to header because our JSX element is containing almost all of the header of the application. ```js const header = (

Welcome to 30 Days Of React

Getting Started React

JavaScript Library

) ``` Let us keep adding more elements. Additional HTML elements to display the author name and year. ```js const header = (

Welcome to 30 Days Of React

Getting Started React

JavaScript Library

Asabeneh Yetayeh

Oct 2, 2020
) ``` As you can see the _header_ element is a parent element for all the inner HTML elements and JSX must be wrapped by an outer parent element. Without the _header_ HTML element or other parent HTML element the above JSX is invalid. #### Commenting a JSX element We comment codes for different reasons and it is also good to know how to comment out JSX elements in React. ```js { /*

Welcome to 30 Days Of React

Getting Started React

JavaScript Library

Asabeneh Yetayeh

Oct 2, 2020
*/ } ``` #### Rendering a JSX Element To render a JSX element to HTML document, we should first create an index HTML. The index.html is the only HTML file you will have in any React Application. That is why we say that every React Application is a single page application. Let us create an index.html file. We can get started with React in two ways - either by using CDN or create-react-app. The create-react-app creates a React project boilerplate outbox and because of that, many people do have a hard time to understand how React works. In order to make things clear for absolute beginners I would like to start with a CDN. We use CDN only in this section and we will use the create-reap-app in the rest of the challenge and I also recommend you to use only create-react-app all the time. ```html 30 Days Of React Challenge
``` As you can see from the above index.html, we have one div with a class root and script. The root _div_ is the gateway to connect all react components to the index.html. In the script tag we will write our JavaScript, but the script _type_ will be _babel_. Babel will _transpile_ the react JSX to pure JavaScript on the browser. Let us add babel to the script. Inside the babel, we can write any pure JavaScript, JSX and in general any React code. ```html 30 Days Of React Challenge
``` The babel library is linked to our document and now we can make use of it. The next step is importing _React_ and _ReactDOM_ using CDN or link. In order to link React and ReactDOM, we attach both packages from CDN to the body of index.html. To test if React is linked to the index.html, try to check it by doing console.log(React). Open the browser console and you should get an object. If you see an object containing React methods then you managed to link your project with React CDN and you are ready to use React. ```html 30 Days Of React Challenge
``` Now the index.html has everything we need to write React code. Let us get the root element using document.querySelect('.root') and assign it to a variable name rootElement. The is the only place we directly interact with DOM. Now, you knew JSX and JSX element. Let us render the JSX element on the browser, in order to do so we need the React and ReactDOM library. In addition to the React and ReactDOM we need babel to transpile the JSX to JavaScript code. The ReactDOM package has a method render. The render method takes two arguments:a JSX element or a component and the root document. See the code below. [Live on code pen](https://codepen.io/Asabeneh/full/JjdbjqK). ```html 30 Days Of React Challenge
``` ![Rendering JSX](../images/rendering_jsx.png) Let us render more content. To render more content, the JSX element should have more HTML elements. For instance, we can create a header of a website and header may have a title, subtitle, author or date etc. Remember, we can render only one JSX element at a time. [Live on code pen](https://codepen.io/Asabeneh/full/QWbGWeY). ```html 30 Days Of React Challenge
``` ![Rendering more content](../images/rendering_more_jsx_content_.png) We have created a JSX element for the header of the website. How about the main and the footer for the website? Similar to the header, let us create a JSX element for the main and the footer. JSX element for the main part of the website. ```js // JSX element const main = (

Prerequisite to get started react.js:

) ``` JSX element for the footer part of the website. ```js // JSX element const footer = ( ) ``` Now, we have three JSX elements: the header, main and footer. The best way to render all of the three JSX elements is by wrapping them all in a parent JSX element or putting them in an array. To include JSX element inside another JSX element we use the curly bracket, {} and call the name of the JSX inside the curly bracket. ```js // JSX element for the header part of the website const header = (

Welcome to 30 Days Of React

Getting Started React

JavaScript Library

Asabeneh Yetayeh

Oct 2, 2020
) // JSX element for the main part of the website const main = (

Prerequisite to get started react.js:

) // JSX element for the footer part of the website const footer = ( ) // JSX element which contain all, it is a container or parent const app = (
{header} {main} {footer}
) ``` Now, let us put everything together and render it to the browser. [Live on code pen](https://codepen.io/Asabeneh/full/MWwbYWg). ```html 30 Days Of React Challenge
``` ![Rendering Multiple JSX Elements](../images/rendering_multiple_jsx_elements.png) Let us apply some style to our JSX elements and see the result. ![Styling JSX Element](../images/styling_jsx_element.png). Now, lets us apply style the header part only [Live on code pen](https://codepen.io/Asabeneh/full/ZEGBYBG). #### Style and className in JSX So far, we did not apply any style in the JSX elements. Now, let us add style to our JSX elements. Inline style became very popular after the emergence of react. Let us add border to the header JSX element. To add style to a JSX element we use inline style or className. We inject the style object using {}. Every CSS property becomes a key and every CSS property value becomes a value for the the object. For instance, in the example below, border is a key and '2px solid orange' is a value, color is a key and 'black' is a value, fontSize is a key and '18px' is a value. All two word CSS properties will change to camelCase when we use them as key in the CSS object in React or JavaScript.[Live on code pen](https://codepen.io/Asabeneh/full/ZEGBYbY). ```js const header = (

Welcome to 30 Days Of React

Getting Started React

JavaScript Library

Asabeneh Yetayeh

Oct 2, 2020
) // or we can write it this way const style = { border: '2px solid orange', color: 'black', fontSize: '18px' } const header = (

Welcome to 30 Days Of React

Getting Started React

JavaScript Library

Asabeneh Yetayeh

Oct 2, 2020
) ``` It is good practice to open the browser console while you are developing your application to know, if everything goes well. Let us keep styling all the JSX elements we have created: the header, main and the footer. We can also use regular internal styling to style our application. Using regular style, to target an HTML element we use tag name, id, class, an attribute and other methods. It is very common in the React developer community - people use classes quite a lot instead of id. In this material, I will use only class instead of id. In JSX element we write className instead of class because class is a reserved word in JavaScript. Similar to className, htmlFor instead of for in label tag. See the example below. ```js const title =

Getting Started React

const inputField = (
) ``` The id used in the input element is not for styling purpose, instead to refer the label to the input field. If class is used instead of className or for instead of htmlFor you will see such kind of warning. ![Class Name warning](../images/className_warning.png) Now, you know how to use the inline style and how to use className. Let us style all the JSX elements. ```html 30 Days Of React Challenge
``` ![Styling all JSX elements](../images/styling_all_jsx_elements.png) Instead of style object using regular styling method is more easy than the one above. Now, let us use internal style to style all the JSX. It is also possible to use external styling method. [Live on code pen](https://codepen.io/Asabeneh/full/QWbGwge) ```html 30 Days Of React Challenge
``` ![Internal Style](../images/internal_style.png) #### Injecting data to a JSX Element So far, we used static data on the JSX elements, but we can also pass different data types as a dynamic data. The dynamic data could be string, number, boolean, array or object. Let us see each of the data types step by step. To inject data to a JSX we use the {} bracket. ```js const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const authorFirstName = 'Asabeneh' const authorLastName = 'Yetayeh' const date = 'Oct 1, 2020' // JSX element, header const header = (

{welcome}

{title}

{subtitle}

Instructor: {authorFirstName} {authorLastName}

Date: {date}
) ``` Similar to the header JSX element, we can implement data injection to main and footer JSX elements. ##### Injecting a string to a JSX Element In this section we inject only strings ```js const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const firstName = 'Asabeneh' const lastName = 'Yetayeh' const date = 'Oct 2, 2020' // JSX element, header // JSX element, header const header = (

{welcome}

{title}

{subtitle}

Instructor: {firstName} {lastName}

Date: {date}
) ``` ##### Injecting a number to a JSX Element ```js const numOne = 3 const numTwo = 2 const result = (

{numOne} + {numTwo} = {numOne + numTwo}

) const yearBorn = 1820 const currentYear = new Date().getFullYear() const age = currentYear - yearBorn const personAge =

{age}

``` As you can see in the example above, it is possible to do some arithmetic calculations and ternary operations. ##### Injecting an array to a JSX Element To give an example for an array, let us change the HTML, CSS, JavaScript to an array and inject it to the main JSX element below. We will cover more in much detail later, in rendering lists section. ```js const techs = ['HTML', 'CSS', 'JavaScript'] // JSX element, main const main = (

Prerequisite to get started{' '} react.js :

) ``` ##### Injecting an object to a JSX Element We can inject string, number, boolean, array data to JSX but we cannot directly inject an object. We should extract object values first or destructure the content of the object before we inject the data to the JSX element. For instance, let us write firstName and lastName inside an object and extract them to use them inside JSX. Now, let us put everything together. Here, in the example below, the data is injected dynamically to the JSX. [Live on code pen](https://codepen.io/Asabeneh/full/YzXWgpZ) ```html 30 Days Of React Challenge
``` ![Dynamic Data](../images/dynamic_data.png) As you can see the lists are all in one line. Therefore, we should format the list the way we want, before we inject it to JSX. In order to format the list, we should modify the array before we will inject it to JSX. We can modify the array using _map_. As a react developer you should have a very good understanding of functional programming(map, filter, reduce, find, some, every). If you don't have good understanding of functional programming, check out day 1. ```js const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) ``` In the following code example, the list is now containing list elements and it is formatted properly. ```html 30 Days Of React Challenge
    ``` Rendering lists ![List Id](../images/map_list_id.png) As you can see above, now the lists are formatted properly, but there is a warning on the console, which says each list child should have a unique key. In the array, we do not have id, but it is common to pass id as a unique value, when you have id in your data. Now, let us just pass each item with a unique key to remove the warning. ```html 30 Days Of React Challenge
    ``` ![Removing the warning ](../images/removing_unique_id_warning.png) Now, you have a very good understanding of how to create JSX elements and also how to inject data to JSX. In the next section, we will talk about how to use create-react-app and components. Components are more powerful and useful than JSX. 🌕 You are awesome. You have just completed day 2 challenges and you are two steps ahead on your way to greatness. Now do some exercises for your brain and for your muscle. ### Exercises #### Exercises: What is React? 1. What is React? 2. What is a library? 3. What is a single page application? 4. What is a component ? 5. What is the latest version of React? 6. What is DOM? 7. What is React Virtual DOM? 8. What does a web application or a website(composed of) have? #### Exercises: Why React? 1. Why did you chose to use react? 2. What measures do you use to know popularity ? 3. What is more popular, React or Vue ? #### Exercises: JSX 1. What is an HTML element? 2. How to write a self closing HTML element? 3. What is an HTML attribute? Write some of them 4. What is JSX? 5. What is babel? 6. What is a transpiler? #### Exercises: JSX Elements 1. What is a JSX element? 2. Write your name in a JSX element and store it in a name variable 3. Write a JSX element which displays your full name, country, title, gender, email, phone number. Use h1 for the name and p for the rest of the information and store it in a user variable 4. Write a footer JSX element #### Exercises: Inline Style 1. Create a style object for the main JSX 2. Create a style object for the footer and app JSX 3. Add more styles to the JSX elements #### Exercises: Internal Styles 1. Apply different styles to your JSX elements #### Exercise: Inject data to JSX 1. Practice how to make JSX element and injecting dynamic data(string, number, boolean, array, object) 🎉 CONGRATULATIONS ! 🎉 [<< Day 1](../01_Day_JavaScript_Refresher/01_javascript_refresher.md) | [Day 3 >>](../03_Day_Setting_Up/03_setting_up.md) ================================================ FILE: 03_Day_Setting_Up/03_setting_up.md ================================================

    30 Days Of React: Setting Up

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 2](../02_Day_Introduction_to_React/02_introduction_to_react.md) | [Day 4 >>](../04_Day_Components/04_components.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_3.jpg) - [Setting Up](#setting-up) - [Node](#node) - [Module](#module) - [Package](#package) - [Node Package Manager(NPM)](#node-package-managernpm) - [Visual Studio Code](#visual-studio-code) - [Browser](#browser) - [Visual Studio Extensions](#visual-studio-extensions) - [Create React App](#create-react-app) - [Your first React App](#your-first-react-app) - [React Boilerplate](#react-boilerplate) - [Styles in JSX](#styles-in-jsx) - [Injecting data to JSX elements](#injecting-data-to-jsx-elements) - [Importing Media Objects in React](#importing-media-objects-in-react) - [Exercises](#exercises) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # Setting Up In the previous section, we learned about JSX and we accessed the React and ReactDOM package using CDN. However, in real projects instead of CDN you will use the create-react-app package to generate a React project starter(boilerplate). The initial _create-react-app_ was released on Jul 22, 2016. Before this time, developers used to configure webpack with a JavaScript module bundler, babel and all the necessary packages manually and this used to take half an hour or maybe more. Now, create-react-app will take care of everything and you will be in charge of only developing the product, instead of spending too much time configuring and setting up projects. Before we start using different tools, let's have a brief introduction to all the tools we are going to use in this challenge. You do not have to understand everything, but I will try to give a very short introduction to some of the tools and technologies that we use when we work with React. ## Node Node is a JavaScript runtime environment that allows JavaScript to run on the server. Node was created in 2009. Node has played a great role for the growth of JavaScript. The React application starts by default at localhost 3000. The create-react-app has configured a node server for the React Application. That is why we need node and node modules. We will see create-react-app soon. If you do not have node, install it. Install [node.js](https://nodejs.org/en/). ![Node download](../images/download_node.png) After downloading double click and install ![Install node](../images/install_node.png) We can check if node is installed on our local machine, by opening our device terminal or command prompt, and writing the following command: ```sh asabeneh $ node -v v12.18.0 ``` ## Module A single or multiple functions, that can be exported and imported when needed, can be included in a project. In React we do not use link to access modules or packages, instead we import the module. Let's see how to import and export a module or modules: ```js // math.js export const addTwo = (a, b) => a + b export const multiply = (a, b) => a * b export const subtract = (a, b) => a - b export default (function doSomeMath() { return { addTwo, multiply, subtract, } })() ``` Now let's import the _math.js_ modules to a different file: ```js // index.js // to import the doSomeMath from the math.js with or without extension import doSomeMath from './math.js' // to import the other modules // since these modules were not exported as default we have to desctructure import { addTwo, multiply, subtract } from './math.js' import * as everything from './math.js' // to import everything remaining console.log(addTwo(5, 5)) console.log(doSomeMath.addTwo(5, 5)) console.log(everything) ``` After this, when you see _import React from 'react'_ or _import ReactDOM from 'react-dom'_ you will not be surprised. ## Package A Package is a module or a collection of modules. For instance, React, ReactDOM are packages. ## Node Package Manager(NPM) NPM was created in 2010. You do not need to install NPM separately - when you install node you will have also NPM. NPM is a default package manager for Node.js. It allows users to consume and distribute JavaScript modules that are available in the registry. NPM allows to create packages, use packages and distribute packages. NMP also played quite a big role in the growth of JavaScript. Currently, there is more than 350,000 packages in the NPM registry. Let's see the create-react-app on NPM registry. The number of downloads show the popularity of the package. ![NPM create-react-app](../images/npm_registry.png) ## Visual Studio Code We will use Visual Studio Code as a code editor. [Download](https://code.visualstudio.com) and install it if you do not have one yet. ## Browser We will use Google Chrome ## Visual Studio Extensions You may need to install these extensions from Visual Studio Code - Prettier - ESLint - Bracket Pair Colorizer - ES7 React/Redux/GraphQL/React-Native snippets ## Create React App To create a react project you can use one of the following ways. Let's assume you installed node. Open the command line interface (CLI), git bash or terminal on Mac or Linux. Then run the following command. I am using git bash. ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop $ npx create-react-app name-of-your-project ``` If you do not like to write npx every time you create a project you may install create-react-app package globally in your computer using the following command. ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop $ npm install -g create-react-app ``` After you installed create-react-app, you create a React application as follows: ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop $ create-react-app name-of-project ``` # Your first React App ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~ \$ cd Desktop/ ``` ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop \$ npx create-react-app 30-days-of-react ``` ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop \$ cd 30-days-of-react/ ``` ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop/30-days-of-react (master) \$ npm start ``` Now your React app should run at localhost 3000. Go to the App.js and modify the content by writing some text, you will see the latest changes on the browser. To stop the server, press Ctr + C in the CLI. ![React Starting](../images/react_app_starting.png) ## React Boilerplate Let's see the React boilerplate, which has been created by create-react-app. Whenever you create a new project, you run create-react-app and name of the project. In the following React boilerplate, there are three folders: node_modules, public and src. In addition, there are .gitignore, README.md, package.json and yarn.lock. Some of you, instead of yarn.lock, you may have package-lock.json. It is good to know these folders and files. - node_modules - stores all the necessary node packages of the React applications. - Public - index.html - the only HTML file we have in the entire application - favicon.ico - an icon file - manifest.json - is used to make the application a progressive web app - other images - open graph images(open graph images are images which are visible when a link share on social media) - robots.txt - information, if the website allows web scraping - src - App.css, index.css - are different CSS files - index.js - a file which allows to connect all the components with index.html - App.js - A file where we usually import most of the presentational components - serviceWorker.js: is used to add progressive web app features - setupTests.js - to write testing cases - package.json- List of packages the applications uses - .gitignore - React boilerplate comes with git initiated, and the .gitingore allows files and folders not to be pushed to GitHub - README.md - Markdown file to write documentation - yarn.lock or package-lock.json - a means to lock the version of the package ![React Boilerplate](../images/react_boilerplate.png) Now lets remove all the files, which we do not need at the moment, and leave only the files we need right now. After removing most of the files, the structure of the boilerplate looks like this: ![React Boilerplate Cleaned](../images/react_bolier_plate_cleaned.png) Now lets write code on index.js. First of, we should import React and ReactDOM. React allows us to write JSX and ReactDOM to render the JSX on the DOM. ReactDOM has a render method. Let's use all the JSX elements we created on Day 2. The ReactDOM render method takes two parameters, a JSX or a component and the root. ```js //index.js // importing the react and react-dom package import React from 'react' import ReactDOM from 'react-dom' const jsxElement =

    This is a JSX element

    const rootElement = document.getElementById('root') ReactDOM.render(jsxElement, rootElement) ``` ```html 30 Days Of React App
    ``` If your application is not running, go to your project folder and run the following command ```sh Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop/30-days-of-react (master) \$ npm start ``` If you do not have any bugs, your React app will be launched on the browser. ![JSX using create react app](../images/jsx_use_create_react_app.png) Let's write more JSX elements and render them on the browser. This expression is a JSX element which is made of h2 HTML element. ```js const title =

    Getting Started React

    ``` Let's add more content to the previous JSX and change the name to header. ```js const header = (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    ) ``` Let's render this to the browser, in order to do so, we need ReactDOM. ```js //index.js // importing the react and react-dom package import React from 'react' import ReactDOM from 'react-dom' const header = (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 2, 2020
    ) const rootElement = document.getElementById('root') ReactDOM.render(header, rootElement) ``` ![JSX using create react app](../images/rendering_more_jsx_content_create_react_app.png) Now, lets add all the JSX we created on Day 2. ```js //index.js // importing the react and react-dom package import React from 'react' import ReactDOM from 'react-dom' // JSX element, header const header = (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 2, 2020
    ) // JSX element, main const main = (

    Prerequisite to get started react.js:

    ) // JSX element, footer const footer = ( ) // JSX element, app, a container or a parent const app = (
    {header} {main} {footer}
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package // ReactDOM has the render method and the render method takes two argument ReactDOM.render(app, rootElement) // or // ReactDOM.render([header, main, footer], rootElement) ``` ![JSX using create react app to render more jsx](../images/rendering_multiple_jsx_elements_create-react_app.png) ## Styles in JSX Let's apply style to the JSX elements. We can style JSX either using inline, internal or external CSS styles. Now, let's apply inline styles to each JSX element. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' const headerStyles = { backgroundColor: '#61DBFB', fontFamily: 'Helvetica Neue', padding: 25, lineHeight: 1.5, } // JSX element, header const header = (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 2, 2020
    ) // JSX element, main const mainStyles = { backgroundColor: '#F3F0F5', } const main = (

    Prerequisite to get started react.js:

    ) const footerStyles = { backgroundColor: '#61DBFB', } // JSX element, footer const footer = ( ) // JSX element, app const app = (
    {header} {main} {footer}
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(app, rootElement) ``` ![Inline styling JSX](../images/styling_jsx_inline_create_react_app.png) Now, lets apply an internal style, we put all the CSS in the header of the index.html. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // JSX element, header const header = (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Instructor: Asabeneh Yetayeh

    Date: Oct 1, 2020
    ) // JSX element, main const main = (

    Prerequisite to get started{' '} react.js :

    ) // JSX element, footer const footer = ( ) // JSX element, app const app = (
    {header} {main} {footer}
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(app, rootElement) ``` ![Inline styling JSX](../images/js_internal_style_create_react_app.png) ## Injecting data to JSX elements ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // To get the root element from the HTML document // JSX element, header const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const author = { firstName: 'Asabeneh', lastName: 'Yetayeh', } const date = 'Oct 2, 2020' // JSX element, header const header = (

    {welcome}

    {title}

    {subtitle}

    Instructor: {author.firstName} {author.lastName}

    Date: {date}
    ) const numOne = 3 const numTwo = 2 const result = (

    {numOne} + {numTwo} = {numOne + numTwo}

    ) const yearBorn = 1820 const currentYear = new Date().getFullYear() const age = currentYear - yearBorn const personAge = (

    {' '} {author.firstName} {author.lastName} is {age} years old

    ) // JSX element, main const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) // JSX element, main const main = (

    Prerequisite to get started{' '} react.js :

    {result} {personAge}
    ) const copyRight = 'Copyright 2020' // JSX element, footer const footer = ( ) // JSX element, app const app = (
    {header} {main} {footer}
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(app, rootElement) ``` ![Inline styling JSX](../images/inecting_data_to_jsx_create_react_app.png) ## Importing Media Objects in React How do we import images, video and audio in React? Let's see how we import images first. Create images folder in the src folder and save an image inside. For instance let's save asabeneh.jpg image and let's import this image to index.js. After importing we will inject it to a JSX expression, user. See the code below. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' const user = (
    asabeneh image
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(user, rootElement) ``` ![Rendering image](../images/rendering_image.png) Let's inject the user inside the main JSX element and see the result: ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // To get the root element from the HTML document import asabenehImage from './images/asabeneh.jpg' // JSX element, header const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const author = { firstName: 'Asabeneh', lastName: 'Yetayeh', } const date = 'Oct 2, 2020' // JSX element, header const header = (

    {welcome}

    {title}

    {subtitle}

    Instructor: {author.firstName} {author.lastName}

    Date: {date}
    ) const numOne = 3 const numTwo = 2 const result = (

    {numOne} + {numTwo} = {numOne + numTwo}

    ) const yearBorn = 1820 const currentYear = new Date().getFullYear() const age = currentYear - yearBorn const personAge = (

    {' '} {author.firstName} {author.lastName} is {age} years old

    ) // JSX element, main const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) const user = (
    asabeneh image
    ) // JSX element, main const main = (

    Prerequisite to get started{' '} react.js :

    {result} {personAge} {user}
    ) const copyRight = 'Copyright 2020' // JSX element, footer const footer = ( ) // JSX element, app const app = (
    {header} {main} {footer}
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(app, rootElement) ``` ![All JSX together final](../images/all_jsx_final.png) The boilerplate code can be found [here](../03/../03_Day_Setting_Up/30-days-of-react_boilerplate) # Exercises ## Exercises: Level 1 1. What is a module? 2. What is package? 3. What is the difference between a module and a package. 4. What is NPM? 5. What is Webpack? 6. How do you create a new React project? 7. What are the files and folders inside a project folder(package.json, package-lock.json or yarn.lock, .gitignore,node_modules and public)? 8. What is your favorite code editor (I believe that it is Visual Studio Code)? 9. Add different Visual Studio Code extensions to improve your productivity(eg. prettier, ESLint etc). 10. Try to make a different custom module in a different file and import it to index.js. ## Exercises: Level 2 1. Import and render the following images ![Front end](../images/frontend_technologies.png) 2. Use h1, p, input and button HTML elements to create the following design using JSX ![News Letter](../images/news_letter_design.png) ## Exercises: Level 3 1. Design the following user card. ![User Card](../images/user_card_design_jsx.png) 🎉 CONGRATULATIONS ! 🎉 [<< Day 2](../02_Day_Introduction_to_React/02_introduction_to_react.md) | [Day 4 >>](../04_Day_Components/04_components.md) ================================================ FILE: 03_Day_Setting_Up/03_setting_up_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 03_Day_Setting_Up/03_setting_up_boilerplate/README.md ================================================ # 30 Days of React App: Day 3 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 03_Day_Setting_Up/03_setting_up_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 03_Day_Setting_Up/03_setting_up_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 03_Day_Setting_Up/03_setting_up_boilerplate/src/index.js ================================================ // index.js import React from 'react' import ReactDOM from 'react-dom' // To get the root element from the HTML document import asabenehImage from './images/asabeneh.jpg' // to import the doSomeMath from the math.js with or without extension import doSomeMath from './math.js' // to import the other modules // since these modules were not exported as default we have to desctructure import { addTwo, multiply, subtract } from './math.js' import * as everything from './math.js' console.log(addTwo(5, 5)) console.log(doSomeMath.addTwo(5, 5)) console.log(everything) // JSX element, header // JSX element, header const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const author = { firstName: 'Asabeneh', lastName: 'Yetayeh', } const date = 'Oct 2, 2020' // JSX element, header const header = (

    {welcome}

    {title}

    {subtitle}

    Instructor: {author.firstName} {author.lastName}

    Date: {date}
    ) const numOne = 3 const numTwo = 2 const result = (

    {numOne} + {numTwo} = {numOne + numTwo}

    ) const yearBorn = 1820 const currentYear = new Date().getFullYear() const age = currentYear - yearBorn const personAge = (

    {' '} {author.firstName} {author.lastName} is {age} years old

    ) // JSX element, main const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) const user = (
    asabeneh image
    ) // JSX element, main const main = (

    Prerequisite to get started{' '} react.js :

    {result} {personAge} {user}
    ) const copyRight = 'Copyright 2020' // JSX element, footer const footer = ( ) // JSX element, app const app = (
    {header} {main} {footer}
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(app, rootElement) ================================================ FILE: 03_Day_Setting_Up/03_setting_up_boilerplate/src/math.js ================================================ // math.js export const addTwo = (a, b) => a + b export const multiply = (a, b) => a * b export const subtract = (a, b) => a - b export default(function doSomeMath() { return { addTwo, multiply, subtract, } })() ================================================ FILE: 04_Day_Components/04_components.md ================================================

    30 Days Of React: Components

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 3](../30-Days-Of-React/03_Day_Setting_Up/03_setting_up.md) | [Day 5 >>](../05_Day_Props/05_props.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_4.jpg) - [Components](#components) - [Big picture of components](#big-picture-of-components) - [JavaScript function](#javascript-function) - [JavaScript Class](#javascript-class) - [Creating React Component](#creating-react-component) - [Functional Component](#functional-component) - [Rendering components](#rendering-components) - [Injecting data to JSX in React Component](#injecting-data-to-jsx-in-react-component) - [Further on Functional components](#further-on-functional-components) - [Exercises: Components](#exercises-components) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # Components A React component is a small, reusable code, which is responsible for one part of the application UI. A React application is an aggregation of components. React can help us to build reusable components. The following diagram shows different components. All the components have different border colors. In React we assemble different components together to create an application. We use JavaScript functions or classes to make components. If we use a function, the component will be a functional component, but if we use a class, the component will be a class-based component. Components can be: - Functional Component / Presentational Component / Stateless Component / Dumb Component - Class Component / Container Component/ Statefull Component / Smart Component The classification of components above does not work for the latest version of React, but it is good to know the former definition and how the previous versions work. So, let us change all the JSX to components. Components in React are JavaScript functions or classes, that return a JSX. Component name must start with an uppercase, and if the name is two words, it should be CamelCase - a camel with two humps. ## Big picture of components In the previous section we agreed, that a website or an application is made of buttons, forms, texts, media objects, header, section, article and footer. If we have a million-dollar button, we can use this button all the time, instead of recreating it all over again, whenever we need a button. The same goes for input fields, forms, header or footer. That is where the power of the component comes. In the following diagram, the header, main and footer are components. Inside the main there is also a user card component and a text section component. All the different colors represent different components. How many colors do you see? Each color represent a single component. We have five components in this diagram. ![Components](../images/components_example.png) Before we jump into React components, let's do some functions and class refreshers. ## JavaScript function A JavaScript function could be either a regular function or an arrow function. These functions are not exactly the same there is a slight difference between them. ```js const getUserInfo = (firstName, lastName, country, title, skills) => { return `${firstName} ${lastName}, a ${title} developer based in ${country}. He knows ${skills.join( ' ' )} ` } // When we call this function we need parameters const skills = ['HTML', 'CSS', 'JS', 'React'] console.log( getUserInfo('Asabeneh', 'Yetayeh', 'Finland', 'FullStack Developer', skills) ) ``` ## JavaScript Class A class is a blueprint of an object. We instantiate a class to create different objects. In addition, we can create children, by inheriting all the methods and properties of the parent. ```js class Parent { constructor(firstName, lastName, country, title) { // we bind the params with this class object using this keyword this.firstName = firstName this.lastName = lastName this.country = country this.title = title } getPersonInfo() { return `${this.firstName} ${this.lastName}, a ${this.title} developer base in ${this.country} ` } parentMethod() { // code goes here } } const p1 = new Parent('Asabeneh', 'Yetayeh', 'Finland', 'FullStack Developer') class Child extends Parent { constructor(firstName, lastName, country, title, skills) { super(firstName, lastName, country, title) this.skills = skills // we bind the child params with the this keyword to this child object } getSkills() { let len = this.skills.length return len > 0 ? this.skills.join(' ') : 'No skills found' } childMethod() { // code goes here } } const skills = ['HTML', 'CSS', 'JS', 'React'] const child = new Child( 'Asabeneh', 'Yetayeh', 'Finland', 'FullStack Developer', skills ) ``` We just briefly covered function and class. React component is made of JavaScript functions or classes, so let's make a React component now. ## Creating React Component ### Functional Component Using a JavaScript function, we can make a functional React component. ```js // React component syntax // it can be arrow function, function declaration or function expression const jsx = Content const ComponentName = () => { return jsx } ``` The following expression is a JSX element. ```js // JSX element, header const header = (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 3, 2020
    ) // React Component const Header = () => { return header } // or we can just return the JSX const Header = () => { return (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 3, 2020
    ) } // Even th above code can be written like this // Explicitly returning the JSX const Header = () => (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 3, 2020
    ) ``` ### Rendering components Now, lets change all the JSX elements we had to components. When we call JSX element we use curly brackets and when we call components we do as follows . If we pass an attribute, when we call the component name, we call it props(). We will talk about props in another section.[Live on code pen](https://codepen.io/Asabeneh/full/wvaKKEM) Let's render first the _Header_ component. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // Header Component const Header = () => (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 3, 2020
    ) const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(
    , rootElement) ``` Now, let's create an App component , that will wrap the Header, Main and Footer. Then the App component will be render on the DOM. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' // Header Component const Header = () => (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 3, 2020
    ) // User Card Component const UserCard = () => (
    asabeneh image

    Asabeneh Yetayeh

    ) // TechList Component const TechList = () => { const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } // Main Component const Main = () => (

    Prerequisite to get started react.js:

    ) // Footer Component const Footer = () => (

    Copyright 2020

    ) // The App, or the parent or the container component const App = () => (
    ) const rootElement = document.getElementById('root') // we render the App component using the ReactDOM package ReactDOM.render(, rootElement) ``` ![Rendering Components](../images/rendering_componnets.png) ### Injecting data to JSX in React Component So far, we used static data on the JSX elements. Now let's pass different data types as dynamic data. The dynamic data could be strings, numbers, booleans, arrays or objects. Let us see each of the data types step by step. To inject data to a JSX we use the {} bracket. In this section we inject only strings ```js import React from 'react' import ReactDOM from 'react-dom' const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const firstName = 'Asabeneh' const lastName = 'Yetayeh' const date = 'Oct 3, 2020' // JSX element, header const header = () => { return (

    {welcome}

    {title}

    {subtitle}

    Instructor: {firstName} {lastName}

    Date: {date}
    ) } const rootElement = document.getElementById('root') // we render the App component using the ReactDOM package ReactDOM.render(
    , rootElement) ``` Similar to the Header component we can implement to Main and Footer component. ```js // To get the root element from the HTML document const rootElement = document.querySelector('.root') // JSX element, header const welcome = 'Welcome to 30 Days Of React Challenge' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const author = { firstName: 'Asabeneh', lastName: 'Yetayeh', } const date = 'Oct 2, 2020' // JSX element, header const Header = () => (

    {welcome}

    {title}

    {subtitle}

    Instructor: {author.firstName} {author.lastName}

    Date: {date}
    ) const numOne = 3 const numTwo = 2 const result = (

    {numOne} + {numTwo} = {numOne + numTwo}

    ) const yearBorn = 1820 const currentYear = 2020 const age = currentYear - yearBorn const personAge = (

    {' '} {author.firstName} {author.lastName} is {age} years old

    ) // User Card Component const UserCard = () => (
    asabeneh image

    {author.firstName} {author.lastName}

    ) // JSX element, main const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) // JSX element, main const Main = () => (

    Prerequisite to get started{' '} react.js :

      {techsFormatted}
    {result} {personAge}
    ) const copyRight = '2020' // JSX element, footer const Footer = () => (

    Copyright ©{copyRight}

    ) // JSX element, app const app = () => (
    ) // we render the App component using the ReactDOM package ReactDOM.render(, rootElement) ``` ### Further on Functional components We have transformed all the JSX elements of Day 2 to functional components, and by now you are very familiar with components. Let's create more components. What is the smallest size of a component? A component that returns only a single HTML as JSX is considered as a small component. A button component or an alert box component, or just an input field component. ```js const Button = () => ``` The _Button_ component is made of a single HTML button element. Let's style this button using JavaScript style object. All CSS properties should be camelCase to make a JavaScript CSS object. If we pass a number without unit as CSS value, it is considered as px. See the example below. ```js const buttonStyles = { padding: '10px 20px', background: 'rgb(0, 255, 0', border: 'none', borderRadius: 5, } const Button = () => ``` The Button component is a dumb component, because it does not take any parameters and we cannot change the action text dynamically. We need to pass props to the button, to change the value dynamically. We will see props in the next section. Before we close today's lesson let's make another, more functional component, which displays a random hexadecimal number. ```js import React from 'react' import ReactDOM from 'react-dom' // Hexadecimal color generator const hexaColor = () => { let str = '0123456789abcdef' let color = '' for (let i = 0; i < 6; i++) { let index = Math.floor(Math.random() * str.length) color += str[index] } return '#' + color } const HexaColor = () =>
    {hexaColor()}
    const rootElement = document.getElementById('root') // we render the App component using the ReactDOM package ReactDOM.render(, rootElement) ``` # Exercises: Components ## Exercises: Level 1 1. What is the difference between a regular function and an arrow function? 2. What is a React Component? 3. How do you make a React functional component? 4. What is the difference between a pure JavaScript function and a functional component? 5. How small is a React component? 6. Can we make a button or input field component? 7. Make a reusable Button component. 8. Make a reusable InputField component. 9. Make a reusable alert box component with one div parent element and one p child element of the div(warning alert box, success alert box). ## Exercises: Level 2 1. Create functional components and display the following images ![Front end](../images/frontend_technologies.png) 2. Use functional component to create the following design ![News Letter](../images/news_letter_design.png) ## Exercises: Level 3 1. Use the given hexadecimal color generator in the example to create these random colors ![Hexadecimal colors](../images/hexadecimal_color_exercise.png) 2. Use functional component to design the following user card. ![User Card](../images/user_card_design_jsx.png) 🎉 CONGRATULATIONS ! 🎉 [<< Day 3](../30-Days-Of-React/03_Day_Setting_Up/03_setting_up.md) | [Day 5 >>](../05_Day_Props/05_props.md) ================================================ FILE: 04_Day_Components/04_components_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 04_Day_Components/04_components_boilerplate/README.md ================================================ # 30 Days of React App: Day 4 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 04_Day_Components/04_components_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 04_Day_Components/04_components_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 04_Day_Components/04_components_boilerplate/src/index.js ================================================ // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' const hexaColor = () => { let str = '0123456789abcdef' let color = '' for (let i = 0; i < 6; i++) { let index = Math.floor(Math.random() * str.length) color += str[index] } return '#' + color } const HexaColor = () => { const bgColor = hexaColor() const styles = { height: '100px', display: 'flex', 'justify-content': 'center', 'align-items': 'center', fontFamily: 'Montserrat', margin: '2px auto', borderRadius: '5px', width: '75%', border: '2px solid black', } return (

    {bgColor}

    ) } // Header Component const Header = () => (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 3, 2020
    ) // User Card Component const UserCard = () => (
    asabeneh image

    Asabeneh Yetayeh

    ) // TechList Component const TechList = () => { const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } const buttonStyles = { padding: '10px 20px', background: 'rgb(0, 255, 0)', border: 'none', borderRadius: 5, } const Button = () => // Main Component const Main = () => (

    Prerequisite to get started react.js:

    {/* Generate two different hexa colors every time */}
    ) // Footer Component const Footer = () => (

    Copyright 2020

    ) // The App, or the parent or the container component const App = () => (
    ) const rootElement = document.getElementById('root') // we render the App component using the ReactDOM package ReactDOM.render(, rootElement) ================================================ FILE: 05_Day_Props/05_props.md ================================================

    30 Days Of React: Props

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 4](../04_Day_Component/04_components.md) | [Day 6 >>](../06_Day_Map_List_Keys/06_map_list_keys.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_5.jpg) - [Props](#props) - [Props in Functional Component](#props-in-functional-component) - [What is props?](#what-is-props) - [Props object](#props-object) - [Different data type props](#different-data-type-props) - [String props type](#string-props-type) - [Number props type](#number-props-type) - [Boolean props type](#boolean-props-type) - [Array props type](#array-props-type) - [Object props type](#object-props-type) - [Function prop types](#function-prop-types) - [Destructuring props](#destructuring-props) - [propTypes](#proptypes) - [defaultProps](#defaultprops) - [Exercises: Components and Props](#exercises-components-and-props) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # Props ## Props in Functional Component In the previous day, we saw how to inject different data types to React component JSX. Now, let us see how we use it in component and also how to pass different data as props. ## What is props? Props is a special keyword in React that stands for properties and is being used to pass data from one component to another and mostly from parent component to child component. We can say props is a data carrier or a means to transport data. I hope you are familiar with the JavaScript function. Most of the time, functions with parameters are smart and they can take dynamic data likewise props is a way we pass data or parameter to a component. Let's see the difference between a function and a component. ```js // function syntax const getUserInfo = (firstName, lastName, country) => { return `${firstName} ${lastName}. Lives in ${country}.` } // calling a functons getUserInfo('Asabeneh', 'Yeteyeh', 'Finland') //component syntax // User component, component should start with an uppercase const User = (props) => { return (

    {props.firstName} {props.lastName}

    {props.country}
    ) } // calling or instantiating a component, this component has three properties and we call them props:firstName, lastName, country ``` In the previous section, we injected data as follows and today we will change these data to props. ```js const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const author = { firstName: 'Asabeneh', lastName: 'Yetayeh', } const date = 'Oct 4, 2020' // Header Component const Header = () => (

    {welcome}

    {title}

    {subtitle}

    {author.firstName} {author.lastName}

    {date}
    ) ``` Instead of injecting data we can also pass the data as props. React props are similar to parameters in functions. ## Props object React props is an object which you get instantly when you create a React component. Before we pass properties to the component, let's check what do we get in the props object. ```js import React from 'react' import ReactDOM from 'react-dom' // Header Component const Header = (props) => { console.log(props) // empty object, {} return (

    {welcome}

    {title}

    {subtitle}

    {author.firstName} {author.lastName}

    {date}
    ) } // The App, or the parent or the container component // Functional Component const App = () => { return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` In the above console.log(props), you would get an empty object({}). That means if you do not pass any attributes or properties when you instantiate the component, the props will be empty otherwise it will be populated with the data you passed as attributes and the proper name of these attributes are props. Let's start with a simple example. In the example below, the welcome string has been passed as props in the Header components. ```js import React from 'react' import ReactDOM from 'react-dom' // Header Component const Header = (props) => { console.log(props) // {welcome:'Welcome to 30 Days Of React'} return (

    {props.welcome}

    ) } // The App, or the parent or the container component // Functional Component const App = () => { return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Now, when you do console.log(props) you should get the following object, that means the welcome property we passed to the Header component can be found inside the props object. ```js { welcome: 'Welcome to 30 Days Of React' } ``` As you can see in the above code, we passed only single props to Header component, the welcome props. A component can have one or many props. Props could be different data types. It could be a string, number, boolean, array, object or a function. We will cover different kind of props in the next sections. ### Different data type props ### String props type The data type of the props we pass an attribute to the component is a string. ```js import React from 'react' import ReactDOM from 'react-dom' // Header Component const Header = (props) => { console.log(props) return (

    {props.welcome}

    {props.title}

    {props.subtitle}

    {props.firstName} {props.lastName}

    {props.date}
    ) } // The App, or the parent or the container component // Functional Component const App = () => (
    ) const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` If you check on the browser console, you will get the following object. ```js { firstName: "Asabeneh", lastName: "Yetayeh", date: "Oct 4, 2020" subtitle: "JavaScript Library" title: "Getting Started React" welcome: "Welcome to 30 Days Of React" } ``` Since you are a JavaScript ninja by now, you know what do do with this object. As you can see from the above example, the value of the props are written statically. However, if we want to apply some logic it is hard to implement with statically written data, so it will be better to use a variable as props. Let's see the following example: ```js import React from 'react' import ReactDOM from 'react-dom' // Header Component const Header = (props) => (

    {props.welcome}

    {props.title}

    {props.subtitle}

    {props.firstName} {props.lastName}

    {props.date}
    ) // The App, or the parent or the container component // Functional Component const App = () => { const welcome = 'Welcome to 30 Days Of React' const title = 'Getting Started React' const subtitle = 'JavaScript Library' const firstName = 'Asabeneh' const lastName = 'Yetayeh' const date = 'Oct 4, 2020' return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ### Number props type Let's use a number props to a component ```js import React from 'react' import ReactDOM from 'react-dom' const Age = (props) =>
    The person is {props.age} years old.
    const Weight = (props) => (

    The weight of the object on earth is {props.weight} N.

    ) // The App, or the parent or the container component // Functional Component const App = () => { let currentYear = 2020 let birthYear = 1820 const age = currentYear - birthYear const gravity = 9.81 const mass = 75 return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ### Boolean props type We can pass boolean data types to a React component. ```js import React from 'react' import ReactDOM from 'react-dom' const Status = (props) => { // ternary operator to check the status of the person let status = props.status ? 'Old enough to drive' : 'Too young for driving' return

    {status}

    } // The App, or the parent or the container component // Functional Component const App = () => { let currentYear = 2020 let birthYear = 2015 const age = currentYear - birthYear // 15 years let status = age >= 18 return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ### Array props type In programming arrays and objects are the most frequently used data structure to solve different problems and store data in a more structured way. Therefore, we encounter data in the form of an array quite often. Let's pass an array as props to a component ```js import React from 'react' import ReactDOM from 'react-dom' const Skills = (props) =>
      {props.skills}
    const App = () => (
    ) const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` If you see the result on the browser, the skills elements needs formatting. Therefore before we render, it should have some elements between each skill. To modify the array and to add a li element we can use map method. You should be very familiar with the functional programming map, filter and reduce to feel good at React if not please go back to day 1 JavaScript refresher. Let's apply map to modify the array. ```js import React from 'react' import ReactDOM from 'react-dom' // Skills Component const Skills = (props) => { // modifying the skills array const skillList = props.skills.map((skill) =>
  • {skill}
  • ) return
      {skillList}
    } const App = () => (
    ) const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` We will go in-depth about list and map in other sections. Now, let's see an object as a props. ### Object props type We may pass an object as props to a React component. Let's see an example. We can change the previous Header props to object. For the time being let's change a few properties for better understanding. ```js import React from 'react' import ReactDOM from 'react-dom' // Header Component const Header = (props) => { return (

    {props.data.welcome}

    {props.data.title}

    {props.data.subtitle}

    ) } // The App, or the parent or the container component // Functional Component const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', } return (
    ) } const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(, rootElement) ``` Now, let's change all the previous Header properties to an object. ```js import React from 'react' import ReactDOM from 'react-dom' const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // Header Component const Header = (props) => { return (

    {props.data.welcome}

    {props.data.title}

    {props.data.subtitle}

    {props.data.author.firstName} {props.data.author.lastName}

    {showDate(props.data.date)}
    ) } // The App, or the parent or the container component // Functional Component const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: new Date(), // date needs to be formatted to a human readable format } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` When we use an object as props we usually destructure the data to access the values. Destructuring makes our code easy to read. We will soon see the destructuring of props but before that let's see function as props for a React component. ### Function prop types We can pass a function as props type to a React component. Let's see some examples ```js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = (props) => // The App, or the parent or the container component // Functional Component const App = () => { const sayHi = () => { alert('Hi') } return (
    ) } const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(, rootElement) ``` Even we can write a function inside the curly bracket ```js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = (props) => // The App, or the parent or the container component // Functional Component const App = () => { return (
    ) } const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(, rootElement) ``` Now, lets implement different functions as props ```js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = (props) => // The App, or the parent or the container component // Functional Component const App = () => { const greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` In the above example, onClick is a props to hold the greetPeople function. HTML has onclick, onmouseover, onhover, onkeypress and etc event handlers. In React, these handlers are in camelCase. For instance onClick, onMouseOver, onKeyPress etc. We will cover events in React in detail in other section. Let's see some more functions as props to give a clear understanding how to handle function as props in a React component. This component shows month, date and year as an alert box. ```js import React from 'react' import ReactDOM from 'react-dom' // Function to display time in Mon date, year format eg Oct 4, 2020 const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // A button component const Button = (props) => // The App, or the parent or the container component // Functional Component const App = () => { const handleTime = () => { alert(showDate(new Date())) } const greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Destructuring props By now, I believe you are a JavaScript ninja and you know about destructing arrays and objects. Destructuring code to some extent makes easy to read. Let us destructure the props in Header component. Everything we passed as props is stored in props object. Therefore, props is an object and we can destructure the properties. Let's destructure some of the props we wrote in object props example. We can destructure in many ways: 1. Step by step destructuring ```js import React from 'react' import ReactDOM from 'react-dom' const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // Header Component const Header = (props) => { const data = props.data const { welcome, title, subtitle, author, date } = data const { firstName, lastName } = author return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {showDate(date)}
    ) } // The App, or the parent or the container component // Functional Component const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: new Date(), } return (
    ) } const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(, rootElement) ``` 2. Destructuring in one line ```js import React from 'react' import ReactDOM from 'react-dom' const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // Header Component const Header = (props) => { const data = props.data const { welcome, title, subtitle, author: { firstName, lastName }, date, } = data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {showDate(date)}
    ) } // The App, or the parent or the container component // Functional Component const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: new Date(), } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` 3. Destructuring the props inside the parenthesis ```js import React from 'react' import ReactDOM from 'react-dom' const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // Header Component const Header = ({ data: { welcome, title, subtitle, author: { firstName, lastName }, date, }, }) => { return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {showDate(date)}
    ) } // The App, or the parent or the container component // Functional Component const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: new Date(), } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Now, let's destructure all the components we had and assemble them together. We pass props from one component to another typically from parent to a child component. For instance in the Main component techs, user, greetPeople and handleTime props have been passed from the parent component Main to child components TechList and UserCard. Below, you will get all the codes destructured and cleaned. ```js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' // Fuction to show month date year const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // Header Component const Header = ({ data: { welcome, title, subtitle, author: { firstName, lastName }, date, }, }) => { return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {showDate(date)}
    ) } // TechList Component const TechList = ({ techs }) => { const techList = techs.map((tech) =>
  • {tech}
  • ) return techList } // User Card Component const UserCard = ({ user: { firstName, lastName, image } }) => (
    {firstName}

    {firstName} {lastName}

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 18, color: 'white', } // Main Component const Main = ({ user, techs, greetPeople, handleTime }) => (

    Prerequisite to get started react.js:

    ) // Footer Component const Footer = ({ copyRight }) => (

    Copyright {copyRight.getFullYear()}

    ) // The App, or the parent or the container component // Functional Component const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: new Date(), // date needs to be formatted to a human readable format } const date = new Date() const techs = ['HTML', 'CSS', 'JavaScript'] // copying the author from data object to user variable using spread operator const user = { ...data.author, image: asabenehImage } const handleTime = () => { alert(showDate(new Date())) } const greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## propTypes The propTypes package helps us to assign the data types of the props we passed to a component. ## defaultProps The defaultProps can be used when we want to have some default prop types for a component. We will cover propTypes in detail in other sections. # Exercises: Components and Props ## Exercises: Level 1 1. What is props in a React component ? 2. How do you access props in a React component ? 3. What data types can we pass as props to components ? 4. What is a propTypes? 5. What is a default propTypes? ## Exercises: Level 2 1. Create a functional component and display the following images ![Front end](../images/frontend_technologies.png) 2. Use functional component to create the following design ![News Letter](../images/news_letter_design.png) ## Exercises: Level 3 1. Use the given hexadecimal color generator in the example to create these random colors. If you don't know how to generate the hexadecimal color you can use [dummy data generator](https://www.30daysofreact.com/dummy-data) ![Hexadecimal colors](../images/hexadecimal_color_exercise.png) 2. Use functional component to design the following user card. ![User Card](../images/user_card_design_jsx.png) 🎉 CONGRATULATIONS ! 🎉 [<< Day 4](../04_Day_Component/04_components.md) | [Day 6 >>](../06_Day_Map_List_Keys/06_map_list_keys.md) ================================================ FILE: 05_Day_Props/05_props_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 05_Day_Props/05_props_boilerplate/README.md ================================================ # 30 Days of React App: Day 5 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 05_Day_Props/05_props_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 05_Day_Props/05_props_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 05_Day_Props/05_props_boilerplate/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' // Fuction to show month date year const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // Header Component const Header = ({ data: { welcome, title, subtitle, author: { firstName, lastName }, date, }, }) => { return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {showDate(date)}
    ) } // TechList Component const TechList = ({ techs }) => { const techList = techs.map((tech) =>
  • {tech}
  • ) return techList } // User Card Component const UserCard = ({ user: { firstName, lastName, image } }) => (
    {firstName}

    {firstName} {lastName}

    ) // A button component const Button = ({ text, onClick, style }) => ( ) const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 18, color: 'white', } // Main Component const Main = ({ user, techs, greetPeople, handleTime }) => (

    Prerequisite to get started react.js:

    ) // Footer Component const Footer = ({ copyRight }) => (

    Copyright {copyRight.getFullYear()}

    ) // The App, or the parent or the container component // Functional Component const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: new Date(), // date needs to be formatted to a human readable format } const date = new Date() const techs = ['HTML', 'CSS', 'JavaScript'] // copying the author from data object to user variable using spread operator const user = { ...data.author, image: asabenehImage } const handleTime = () => { alert(showDate(new Date())) } const greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys.md ================================================

    30 Days Of React: Mapping Arrays

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 5](./../05_Day_Props/05_props.md) | [Day 7 >>](../07_Day_Class_Components/07_class_components.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_6.jpg) - [Mapping arrays](#mapping-arrays) - [Mapping and rendering arrays](#mapping-and-rendering-arrays) - [Mapping array of numbers](#mapping-array-of-numbers) - [Mapping array of arrays](#mapping-array-of-arrays) - [Mapping array of objects](#mapping-array-of-objects) - [Key in mapping arrays](#key-in-mapping-arrays) - [Exercises](#exercises) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # Mapping arrays An array is the most frequently used data structure to handle many kinds of problems. In React, we use map to modify an array to list of JSX by adding a certain HTML elements to each element of an array. ## Mapping and rendering arrays Most of the time data is in the form of an array or an array of objects. To render this array or array of objects most of the time we modify the data using _map_. In the previous section, we have rendered the techs list using a map method. In this section, we will see more examples. In the following examples, you will see how we render an array of numbers, an array of strings, an array of countries and an array of skills on the browser. ```js import React from 'react' import ReactDOM from 'react-dom' const App = () => { return (

    Numbers List

    {[1, 2, 3, 4, 5]}
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` If you check the browser, you will see the numbers are attached together in one line. To avoid this, we modify the array and change the array elements to JSX element. See the example below, the array has been modified to a list of JSX elements. ### Mapping array of numbers ```js import React from 'react' import ReactDOM from 'react-dom' const Numbers = ({ numbers }) => { // modifying array to array of li JSX const list = numbers.map((number) =>
  • {number}
  • ) return list } // App component const App = () => { const numbers = [1, 2, 3, 4, 5] return (

    Numbers List

    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ### Mapping array of arrays Let's see how to map array of arrays ```js import React from 'react' import ReactDOM from 'react-dom' const skills = [ ['HTML', 10], ['CSS', 7], ['JavaScript', 9], ['React', 8], ] // Skill Component const Skill = ({ skill: [tech, level] }) => (
  • {tech} {level}
  • ) // Skills Component const Skills = ({ skills }) => { const skillsList = skills.map((skill) => ) console.log(skillsList) return
      {skillsList}
    } const App = () => { return (

    Skills Level

    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ### Mapping array of objects Rendering array of objects ```js import React from 'react' import ReactDOM from 'react-dom' const countries = [ { name: 'Finland', city: 'Helsinki' }, { name: 'Sweden', city: 'Stockholm' }, { name: 'Denmark', city: 'Copenhagen' }, { name: 'Norway', city: 'Oslo' }, { name: 'Iceland', city: 'Reykjavík' }, ] // Country component const Country = ({ country: { name, city } }) => { return (

    {name}

    {city}
    ) } // countries component const Countries = ({ countries }) => { const countryList = countries.map((country) => ) return
    {countryList}
    } // App component const App = () => (

    Countries List

    ) const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ### Key in mapping arrays Keys help React to identify items which have changed, added, or removed. Keys should be given to the elements inside the array to give the elements a stable identity. The key should be unique. Mostly data will come with as an id and we can use id as key. If we do not pass key to React during mapping it raises a warning on the browser. If the data does not have an id we have to find a way to create a unique identifier for each element when we map it. See the following example: ```js import React from 'react' import ReactDOM from 'react-dom' const Numbers = ({ numbers }) => { // modifying array to array of li JSX const list = numbers.map((num) =>
  • {num}
  • ) return list } const App = () => { const numbers = [1, 2, 3, 4, 5] return (

    Numbers List

    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Let's also add in key in countries mapping example. ```js import React from 'react' import ReactDOM from 'react-dom' const countries = [ { name: 'Finland', city: 'Helsinki' }, { name: 'Sweden', city: 'Stockholm' }, { name: 'Denmark', city: 'Copenhagen' }, { name: 'Norway', city: 'Oslo' }, { name: 'Iceland', city: 'Reykjavík' }, ] // Country component const Country = ({ country: { name, city } }) => { return (

    {name}

    {city}
    ) } // countries component const Countries = ({ countries }) => { const countryList = countries.map((country) => ( )) return
    {countryList}
    } const App = () => (

    Countries List

    ) const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` # Exercises ## Exercises: Level 1 1. Why you need to map an array ? 2. Why we need keys during mapping an array ? 3. What is the importance of destructuring your code ? 4. Does destructuring make your code clean and easy to read ? ## Exercises: Level 2 1. In the following design, evens are green, odds are yellow and prime numbers are red. Build the following colors using React component ![Number Generator](../images/day_6_number_generater_exercise.png) 2. Create the following hexadecimal colors using React component ![Number Generator](../images/day_6_hexadecimal_colors_exercise.png) ## Exercises: Level 3 1.Make the following bar group using the given [data](../06_Day_Map_List_Keys/06_map_list_keys_boilerplate/src/data/ten_most_highest_populations.js) ![Ten most highest populations](../images/day_6_ten_highest_populations_exercise.png) 🎉 CONGRATULATIONS ! 🎉 [<< Day 5](./../05_Day_Props/05_props.md) | [Day 7 >>](../07_Day_Class_Components/07_class_components.md) ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys_boilerplate/README.md ================================================ # 30 Days of React App: Day 6 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys_boilerplate/src/data/countries.js ================================================ export const countriesData = [ { name: 'Afghanistan', capital: 'Kabul', languages: ['Pashto', 'Uzbek', 'Turkmen'], population: 27657145, flag: 'https://restcountries.eu/data/afg.svg', currency: 'Afghan afghani', }, { name: 'Åland Islands', capital: 'Mariehamn', languages: ['Swedish'], population: 28875, flag: 'https://restcountries.eu/data/ala.svg', currency: 'Euro', }, { name: 'Albania', capital: 'Tirana', languages: ['Albanian'], population: 2886026, flag: 'https://restcountries.eu/data/alb.svg', currency: 'Albanian lek', }, { name: 'Algeria', capital: 'Algiers', languages: ['Arabic'], population: 40400000, flag: 'https://restcountries.eu/data/dza.svg', currency: 'Algerian dinar', }, { name: 'American Samoa', capital: 'Pago Pago', languages: ['English', 'Samoan'], population: 57100, flag: 'https://restcountries.eu/data/asm.svg', currency: 'United State Dollar', }, { name: 'Andorra', capital: 'Andorra la Vella', languages: ['Catalan'], population: 78014, flag: 'https://restcountries.eu/data/and.svg', currency: 'Euro', }, { name: 'Angola', capital: 'Luanda', languages: ['Portuguese'], population: 25868000, flag: 'https://restcountries.eu/data/ago.svg', currency: 'Angolan kwanza', }, { name: 'Anguilla', capital: 'The Valley', languages: ['English'], population: 13452, flag: 'https://restcountries.eu/data/aia.svg', currency: 'East Caribbean dollar', }, { name: 'Antarctica', capital: '', languages: ['English', 'Russian'], population: 1000, flag: 'https://restcountries.eu/data/ata.svg', currency: 'Australian dollar', }, { name: 'Antigua and Barbuda', capital: "Saint John's", languages: ['English'], population: 86295, flag: 'https://restcountries.eu/data/atg.svg', currency: 'East Caribbean dollar', }, { name: 'Argentina', capital: 'Buenos Aires', languages: ['Spanish', 'Guaraní'], population: 43590400, flag: 'https://restcountries.eu/data/arg.svg', currency: 'Argentine peso', }, { name: 'Armenia', capital: 'Yerevan', languages: ['Armenian', 'Russian'], population: 2994400, flag: 'https://restcountries.eu/data/arm.svg', currency: 'Armenian dram', }, { name: 'Aruba', capital: 'Oranjestad', languages: ['Dutch', '(Eastern) Punjabi'], population: 107394, flag: 'https://restcountries.eu/data/abw.svg', currency: 'Aruban florin', }, { name: 'Australia', capital: 'Canberra', languages: ['English'], population: 24117360, flag: 'https://restcountries.eu/data/aus.svg', currency: 'Australian dollar', }, { name: 'Austria', capital: 'Vienna', languages: ['German'], population: 8725931, flag: 'https://restcountries.eu/data/aut.svg', currency: 'Euro', }, { name: 'Azerbaijan', capital: 'Baku', languages: ['Azerbaijani'], population: 9730500, flag: 'https://restcountries.eu/data/aze.svg', currency: 'Azerbaijani manat', }, { name: 'Bahamas', capital: 'Nassau', languages: ['English'], population: 378040, flag: 'https://restcountries.eu/data/bhs.svg', currency: 'Bahamian dollar', }, { name: 'Bahrain', capital: 'Manama', languages: ['Arabic'], population: 1404900, flag: 'https://restcountries.eu/data/bhr.svg', currency: 'Bahraini dinar', }, { name: 'Bangladesh', capital: 'Dhaka', languages: ['Bengali'], population: 161006790, flag: 'https://restcountries.eu/data/bgd.svg', currency: 'Bangladeshi taka', }, { name: 'Barbados', capital: 'Bridgetown', languages: ['English'], population: 285000, flag: 'https://restcountries.eu/data/brb.svg', currency: 'Barbadian dollar', }, { name: 'Belarus', capital: 'Minsk', languages: ['Belarusian', 'Russian'], population: 9498700, flag: 'https://restcountries.eu/data/blr.svg', currency: 'New Belarusian ruble', }, { name: 'Belgium', capital: 'Brussels', languages: ['Dutch', 'French', 'German'], population: 11319511, flag: 'https://restcountries.eu/data/bel.svg', currency: 'Euro', }, { name: 'Belize', capital: 'Belmopan', languages: ['English', 'Spanish'], population: 370300, flag: 'https://restcountries.eu/data/blz.svg', currency: 'Belize dollar', }, { name: 'Benin', capital: 'Porto-Novo', languages: ['French'], population: 10653654, flag: 'https://restcountries.eu/data/ben.svg', currency: 'West African CFA franc', }, { name: 'Bermuda', capital: 'Hamilton', languages: ['English'], population: 61954, flag: 'https://restcountries.eu/data/bmu.svg', currency: 'Bermudian dollar', }, { name: 'Bhutan', capital: 'Thimphu', languages: ['Dzongkha'], population: 775620, flag: 'https://restcountries.eu/data/btn.svg', currency: 'Bhutanese ngultrum', }, { name: 'Bolivia (Plurinational State of)', capital: 'Sucre', languages: ['Spanish', 'Aymara', 'Quechua'], population: 10985059, flag: 'https://restcountries.eu/data/bol.svg', currency: 'Bolivian boliviano', }, { name: 'Bonaire, Sint Eustatius and Saba', capital: 'Kralendijk', languages: ['Dutch'], population: 17408, flag: 'https://restcountries.eu/data/bes.svg', currency: 'United States dollar', }, { name: 'Bosnia and Herzegovina', capital: 'Sarajevo', languages: ['Bosnian', 'Croatian', 'Serbian'], population: 3531159, flag: 'https://restcountries.eu/data/bih.svg', currency: 'Bosnia and Herzegovina convertible mark', }, { name: 'Botswana', capital: 'Gaborone', languages: ['English', 'Tswana'], population: 2141206, flag: 'https://restcountries.eu/data/bwa.svg', currency: 'Botswana pula', }, { name: 'Bouvet Island', capital: '', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 0, flag: 'https://restcountries.eu/data/bvt.svg', currency: 'Norwegian krone', }, { name: 'Brazil', capital: 'Brasília', languages: ['Portuguese'], population: 206135893, flag: 'https://restcountries.eu/data/bra.svg', currency: 'Brazilian real', }, { name: 'British Indian Ocean Territory', capital: 'Diego Garcia', languages: ['English'], population: 3000, flag: 'https://restcountries.eu/data/iot.svg', currency: 'United States dollar', }, { name: 'United States Minor Outlying Islands', capital: '', languages: ['English'], population: 300, flag: 'https://restcountries.eu/data/umi.svg', currency: 'United States Dollar', }, { name: 'Virgin Islands (British)', capital: 'Road Town', languages: ['English'], population: 28514, flag: 'https://restcountries.eu/data/vgb.svg', currency: '[D]', }, { name: 'Virgin Islands (U.S.)', capital: 'Charlotte Amalie', languages: ['English'], population: 114743, flag: 'https://restcountries.eu/data/vir.svg', currency: 'United States dollar', }, { name: 'Brunei Darussalam', capital: 'Bandar Seri Begawan', languages: ['Malay'], population: 411900, flag: 'https://restcountries.eu/data/brn.svg', currency: 'Brunei dollar', }, { name: 'Bulgaria', capital: 'Sofia', languages: ['Bulgarian'], population: 7153784, flag: 'https://restcountries.eu/data/bgr.svg', currency: 'Bulgarian lev', }, { name: 'Burkina Faso', capital: 'Ouagadougou', languages: ['French', 'Fula'], population: 19034397, flag: 'https://restcountries.eu/data/bfa.svg', currency: 'West African CFA franc', }, { name: 'Burundi', capital: 'Bujumbura', languages: ['French', 'Kirundi'], population: 10114505, flag: 'https://restcountries.eu/data/bdi.svg', currency: 'Burundian franc', }, { name: 'Cambodia', capital: 'Phnom Penh', languages: ['Khmer'], population: 15626444, flag: 'https://restcountries.eu/data/khm.svg', currency: 'Cambodian riel', }, { name: 'Cameroon', capital: 'Yaoundé', languages: ['English', 'French'], population: 22709892, flag: 'https://restcountries.eu/data/cmr.svg', currency: 'Central African CFA franc', }, { name: 'Canada', capital: 'Ottawa', languages: ['English', 'French'], population: 36155487, flag: 'https://restcountries.eu/data/can.svg', currency: 'Canadian dollar', }, { name: 'Cabo Verde', capital: 'Praia', languages: ['Portuguese'], population: 531239, flag: 'https://restcountries.eu/data/cpv.svg', currency: 'Cape Verdean escudo', }, { name: 'Cayman Islands', capital: 'George Town', languages: ['English'], population: 58238, flag: 'https://restcountries.eu/data/cym.svg', currency: 'Cayman Islands dollar', }, { name: 'Central African Republic', capital: 'Bangui', languages: ['French', 'Sango'], population: 4998000, flag: 'https://restcountries.eu/data/caf.svg', currency: 'Central African CFA franc', }, { name: 'Chad', capital: "N'Djamena", languages: ['French', 'Arabic'], population: 14497000, flag: 'https://restcountries.eu/data/tcd.svg', currency: 'Central African CFA franc', }, { name: 'Chile', capital: 'Santiago', languages: ['Spanish'], population: 18191900, flag: 'https://restcountries.eu/data/chl.svg', currency: 'Chilean peso', }, { name: 'China', capital: 'Beijing', languages: ['Chinese'], population: 1377422166, flag: 'https://restcountries.eu/data/chn.svg', currency: 'Chinese yuan', }, { name: 'Christmas Island', capital: 'Flying Fish Cove', languages: ['English'], population: 2072, flag: 'https://restcountries.eu/data/cxr.svg', currency: 'Australian dollar', }, { name: 'Cocos (Keeling) Islands', capital: 'West Island', languages: ['English'], population: 550, flag: 'https://restcountries.eu/data/cck.svg', currency: 'Australian dollar', }, { name: 'Colombia', capital: 'Bogotá', languages: ['Spanish'], population: 48759958, flag: 'https://restcountries.eu/data/col.svg', currency: 'Colombian peso', }, { name: 'Comoros', capital: 'Moroni', languages: ['Arabic', 'French'], population: 806153, flag: 'https://restcountries.eu/data/com.svg', currency: 'Comorian franc', }, { name: 'Congo', capital: 'Brazzaville', languages: ['French', 'Lingala'], population: 4741000, flag: 'https://restcountries.eu/data/cog.svg', currency: 'Central African CFA franc', }, { name: 'Congo (Democratic Republic of the)', capital: 'Kinshasa', languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], population: 85026000, flag: 'https://restcountries.eu/data/cod.svg', currency: 'Congolese franc', }, { name: 'Cook Islands', capital: 'Avarua', languages: ['English'], population: 18100, flag: 'https://restcountries.eu/data/cok.svg', currency: 'New Zealand dollar', }, { name: 'Costa Rica', capital: 'San José', languages: ['Spanish'], population: 4890379, flag: 'https://restcountries.eu/data/cri.svg', currency: 'Costa Rican colón', }, { name: 'Croatia', capital: 'Zagreb', languages: ['Croatian'], population: 4190669, flag: 'https://restcountries.eu/data/hrv.svg', currency: 'Croatian kuna', }, { name: 'Cuba', capital: 'Havana', languages: ['Spanish'], population: 11239004, flag: 'https://restcountries.eu/data/cub.svg', currency: 'Cuban convertible peso', }, { name: 'Curaçao', capital: 'Willemstad', languages: ['Dutch', '(Eastern) Punjabi', 'English'], population: 154843, flag: 'https://restcountries.eu/data/cuw.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Cyprus', capital: 'Nicosia', languages: ['Greek (modern)', 'Turkish', 'Armenian'], population: 847000, flag: 'https://restcountries.eu/data/cyp.svg', currency: 'Euro', }, { name: 'Czech Republic', capital: 'Prague', languages: ['Czech', 'Slovak'], population: 10558524, flag: 'https://restcountries.eu/data/cze.svg', currency: 'Czech koruna', }, { name: 'Denmark', capital: 'Copenhagen', languages: ['Danish'], population: 5717014, flag: 'https://restcountries.eu/data/dnk.svg', currency: 'Danish krone', }, { name: 'Djibouti', capital: 'Djibouti', languages: ['French', 'Arabic'], population: 900000, flag: 'https://restcountries.eu/data/dji.svg', currency: 'Djiboutian franc', }, { name: 'Dominica', capital: 'Roseau', languages: ['English'], population: 71293, flag: 'https://restcountries.eu/data/dma.svg', currency: 'East Caribbean dollar', }, { name: 'Dominican Republic', capital: 'Santo Domingo', languages: ['Spanish'], population: 10075045, flag: 'https://restcountries.eu/data/dom.svg', currency: 'Dominican peso', }, { name: 'Ecuador', capital: 'Quito', languages: ['Spanish'], population: 16545799, flag: 'https://restcountries.eu/data/ecu.svg', currency: 'United States dollar', }, { name: 'Egypt', capital: 'Cairo', languages: ['Arabic'], population: 91290000, flag: 'https://restcountries.eu/data/egy.svg', currency: 'Egyptian pound', }, { name: 'El Salvador', capital: 'San Salvador', languages: ['Spanish'], population: 6520675, flag: 'https://restcountries.eu/data/slv.svg', currency: 'United States dollar', }, { name: 'Equatorial Guinea', capital: 'Malabo', languages: ['Spanish', 'French'], population: 1222442, flag: 'https://restcountries.eu/data/gnq.svg', currency: 'Central African CFA franc', }, { name: 'Eritrea', capital: 'Asmara', languages: ['Tigrinya', 'Arabic', 'English'], population: 5352000, flag: 'https://restcountries.eu/data/eri.svg', currency: 'Eritrean nakfa', }, { name: 'Estonia', capital: 'Tallinn', languages: ['Estonian'], population: 1315944, flag: 'https://restcountries.eu/data/est.svg', currency: 'Euro', }, { name: 'Ethiopia', capital: 'Addis Ababa', languages: ['Amharic'], population: 92206005, flag: 'https://restcountries.eu/data/eth.svg', currency: 'Ethiopian birr', }, { name: 'Falkland Islands (Malvinas)', capital: 'Stanley', languages: ['English'], population: 2563, flag: 'https://restcountries.eu/data/flk.svg', currency: 'Falkland Islands pound', }, { name: 'Faroe Islands', capital: 'Tórshavn', languages: ['Faroese'], population: 49376, flag: 'https://restcountries.eu/data/fro.svg', currency: 'Danish krone', }, { name: 'Fiji', capital: 'Suva', languages: ['English', 'Fijian', 'Hindi', 'Urdu'], population: 867000, flag: 'https://restcountries.eu/data/fji.svg', currency: 'Fijian dollar', }, { name: 'Finland', capital: 'Helsinki', languages: ['Finnish', 'Swedish'], population: 5491817, flag: 'https://restcountries.eu/data/fin.svg', currency: 'Euro', }, { name: 'France', capital: 'Paris', languages: ['French'], population: 66710000, flag: 'https://restcountries.eu/data/fra.svg', currency: 'Euro', }, { name: 'French Guiana', capital: 'Cayenne', languages: ['French'], population: 254541, flag: 'https://restcountries.eu/data/guf.svg', currency: 'Euro', }, { name: 'French Polynesia', capital: 'Papeetē', languages: ['French'], population: 271800, flag: 'https://restcountries.eu/data/pyf.svg', currency: 'CFP franc', }, { name: 'French Southern Territories', capital: 'Port-aux-Français', languages: ['French'], population: 140, flag: 'https://restcountries.eu/data/atf.svg', currency: 'Euro', }, { name: 'Gabon', capital: 'Libreville', languages: ['French'], population: 1802278, flag: 'https://restcountries.eu/data/gab.svg', currency: 'Central African CFA franc', }, { name: 'Gambia', capital: 'Banjul', languages: ['English'], population: 1882450, flag: 'https://restcountries.eu/data/gmb.svg', currency: 'Gambian dalasi', }, { name: 'Georgia', capital: 'Tbilisi', languages: ['Georgian'], population: 3720400, flag: 'https://restcountries.eu/data/geo.svg', currency: 'Georgian Lari', }, { name: 'Germany', capital: 'Berlin', languages: ['German'], population: 81770900, flag: 'https://restcountries.eu/data/deu.svg', currency: 'Euro', }, { name: 'Ghana', capital: 'Accra', languages: ['English'], population: 27670174, flag: 'https://restcountries.eu/data/gha.svg', currency: 'Ghanaian cedi', }, { name: 'Gibraltar', capital: 'Gibraltar', languages: ['English'], population: 33140, flag: 'https://restcountries.eu/data/gib.svg', currency: 'Gibraltar pound', }, { name: 'Greece', capital: 'Athens', languages: ['Greek (modern)'], population: 10858018, flag: 'https://restcountries.eu/data/grc.svg', currency: 'Euro', }, { name: 'Greenland', capital: 'Nuuk', languages: ['Kalaallisut'], population: 55847, flag: 'https://restcountries.eu/data/grl.svg', currency: 'Danish krone', }, { name: 'Grenada', capital: "St. George's", languages: ['English'], population: 103328, flag: 'https://restcountries.eu/data/grd.svg', currency: 'East Caribbean dollar', }, { name: 'Guadeloupe', capital: 'Basse-Terre', languages: ['French'], population: 400132, flag: 'https://restcountries.eu/data/glp.svg', currency: 'Euro', }, { name: 'Guam', capital: 'Hagåtña', languages: ['English', 'Chamorro', 'Spanish'], population: 184200, flag: 'https://restcountries.eu/data/gum.svg', currency: 'United States dollar', }, { name: 'Guatemala', capital: 'Guatemala City', languages: ['Spanish'], population: 16176133, flag: 'https://restcountries.eu/data/gtm.svg', currency: 'Guatemalan quetzal', }, { name: 'Guernsey', capital: 'St. Peter Port', languages: ['English', 'French'], population: 62999, flag: 'https://restcountries.eu/data/ggy.svg', currency: 'British pound', }, { name: 'Guinea', capital: 'Conakry', languages: ['French', 'Fula'], population: 12947000, flag: 'https://restcountries.eu/data/gin.svg', currency: 'Guinean franc', }, { name: 'Guinea-Bissau', capital: 'Bissau', languages: ['Portuguese'], population: 1547777, flag: 'https://restcountries.eu/data/gnb.svg', currency: 'West African CFA franc', }, { name: 'Guyana', capital: 'Georgetown', languages: ['English'], population: 746900, flag: 'https://restcountries.eu/data/guy.svg', currency: 'Guyanese dollar', }, { name: 'Haiti', capital: 'Port-au-Prince', languages: ['French', 'Haitian'], population: 11078033, flag: 'https://restcountries.eu/data/hti.svg', currency: 'Haitian gourde', }, { name: 'Heard Island and McDonald Islands', capital: '', languages: ['English'], population: 0, flag: 'https://restcountries.eu/data/hmd.svg', currency: 'Australian dollar', }, { name: 'Holy See', capital: 'Rome', languages: ['Latin', 'Italian', 'French', 'German'], population: 451, flag: 'https://restcountries.eu/data/vat.svg', currency: 'Euro', }, { name: 'Honduras', capital: 'Tegucigalpa', languages: ['Spanish'], population: 8576532, flag: 'https://restcountries.eu/data/hnd.svg', currency: 'Honduran lempira', }, { name: 'Hong Kong', capital: 'City of Victoria', languages: ['English', 'Chinese'], population: 7324300, flag: 'https://restcountries.eu/data/hkg.svg', currency: 'Hong Kong dollar', }, { name: 'Hungary', capital: 'Budapest', languages: ['Hungarian'], population: 9823000, flag: 'https://restcountries.eu/data/hun.svg', currency: 'Hungarian forint', }, { name: 'Iceland', capital: 'Reykjavík', languages: ['Icelandic'], population: 334300, flag: 'https://restcountries.eu/data/isl.svg', currency: 'Icelandic króna', }, { name: 'India', capital: 'New Delhi', languages: ['Hindi', 'English'], population: 1295210000, flag: 'https://restcountries.eu/data/ind.svg', currency: 'Indian rupee', }, { name: 'Indonesia', capital: 'Jakarta', languages: ['Indonesian'], population: 258705000, flag: 'https://restcountries.eu/data/idn.svg', currency: 'Indonesian rupiah', }, { name: "Côte d'Ivoire", capital: 'Yamoussoukro', languages: ['French'], population: 22671331, flag: 'https://restcountries.eu/data/civ.svg', currency: 'West African CFA franc', }, { name: 'Iran (Islamic Republic of)', capital: 'Tehran', languages: ['Persian (Farsi)'], population: 79369900, flag: 'https://restcountries.eu/data/irn.svg', currency: 'Iranian rial', }, { name: 'Iraq', capital: 'Baghdad', languages: ['Arabic', 'Kurdish'], population: 37883543, flag: 'https://restcountries.eu/data/irq.svg', currency: 'Iraqi dinar', }, { name: 'Ireland', capital: 'Dublin', languages: ['Irish', 'English'], population: 6378000, flag: 'https://restcountries.eu/data/irl.svg', currency: 'Euro', }, { name: 'Isle of Man', capital: 'Douglas', languages: ['English', 'Manx'], population: 84497, flag: 'https://restcountries.eu/data/imn.svg', currency: 'British pound', }, { name: 'Israel', capital: 'Jerusalem', languages: ['Hebrew (modern)', 'Arabic'], population: 8527400, flag: 'https://restcountries.eu/data/isr.svg', currency: 'Israeli new shekel', }, { name: 'Italy', capital: 'Rome', languages: ['Italian'], population: 60665551, flag: 'https://restcountries.eu/data/ita.svg', currency: 'Euro', }, { name: 'Jamaica', capital: 'Kingston', languages: ['English'], population: 2723246, flag: 'https://restcountries.eu/data/jam.svg', currency: 'Jamaican dollar', }, { name: 'Japan', capital: 'Tokyo', languages: ['Japanese'], population: 126960000, flag: 'https://restcountries.eu/data/jpn.svg', currency: 'Japanese yen', }, { name: 'Jersey', capital: 'Saint Helier', languages: ['English', 'French'], population: 100800, flag: 'https://restcountries.eu/data/jey.svg', currency: 'British pound', }, { name: 'Jordan', capital: 'Amman', languages: ['Arabic'], population: 9531712, flag: 'https://restcountries.eu/data/jor.svg', currency: 'Jordanian dinar', }, { name: 'Kazakhstan', capital: 'Astana', languages: ['Kazakh', 'Russian'], population: 17753200, flag: 'https://restcountries.eu/data/kaz.svg', currency: 'Kazakhstani tenge', }, { name: 'Kenya', capital: 'Nairobi', languages: ['English', 'Swahili'], population: 47251000, flag: 'https://restcountries.eu/data/ken.svg', currency: 'Kenyan shilling', }, { name: 'Kiribati', capital: 'South Tarawa', languages: ['English'], population: 113400, flag: 'https://restcountries.eu/data/kir.svg', currency: 'Australian dollar', }, { name: 'Kuwait', capital: 'Kuwait City', languages: ['Arabic'], population: 4183658, flag: 'https://restcountries.eu/data/kwt.svg', currency: 'Kuwaiti dinar', }, { name: 'Kyrgyzstan', capital: 'Bishkek', languages: ['Kyrgyz', 'Russian'], population: 6047800, flag: 'https://restcountries.eu/data/kgz.svg', currency: 'Kyrgyzstani som', }, { name: "Lao People's Democratic Republic", capital: 'Vientiane', languages: ['Lao'], population: 6492400, flag: 'https://restcountries.eu/data/lao.svg', currency: 'Lao kip', }, { name: 'Latvia', capital: 'Riga', languages: ['Latvian'], population: 1961600, flag: 'https://restcountries.eu/data/lva.svg', currency: 'Euro', }, { name: 'Lebanon', capital: 'Beirut', languages: ['Arabic', 'French'], population: 5988000, flag: 'https://restcountries.eu/data/lbn.svg', currency: 'Lebanese pound', }, { name: 'Lesotho', capital: 'Maseru', languages: ['English', 'Southern Sotho'], population: 1894194, flag: 'https://restcountries.eu/data/lso.svg', currency: 'Lesotho loti', }, { name: 'Liberia', capital: 'Monrovia', languages: ['English'], population: 4615000, flag: 'https://restcountries.eu/data/lbr.svg', currency: 'Liberian dollar', }, { name: 'Libya', capital: 'Tripoli', languages: ['Arabic'], population: 6385000, flag: 'https://restcountries.eu/data/lby.svg', currency: 'Libyan dinar', }, { name: 'Liechtenstein', capital: 'Vaduz', languages: ['German'], population: 37623, flag: 'https://restcountries.eu/data/lie.svg', currency: 'Swiss franc', }, { name: 'Lithuania', capital: 'Vilnius', languages: ['Lithuanian'], population: 2872294, flag: 'https://restcountries.eu/data/ltu.svg', currency: 'Euro', }, { name: 'Luxembourg', capital: 'Luxembourg', languages: ['French', 'German', 'Luxembourgish'], population: 576200, flag: 'https://restcountries.eu/data/lux.svg', currency: 'Euro', }, { name: 'Macao', capital: '', languages: ['Chinese', 'Portuguese'], population: 649100, flag: 'https://restcountries.eu/data/mac.svg', currency: 'Macanese pataca', }, { name: 'Macedonia (the former Yugoslav Republic of)', capital: 'Skopje', languages: ['Macedonian'], population: 2058539, flag: 'https://restcountries.eu/data/mkd.svg', currency: 'Macedonian denar', }, { name: 'Madagascar', capital: 'Antananarivo', languages: ['French', 'Malagasy'], population: 22434363, flag: 'https://restcountries.eu/data/mdg.svg', currency: 'Malagasy ariary', }, { name: 'Malawi', capital: 'Lilongwe', languages: ['English', 'Chichewa'], population: 16832910, flag: 'https://restcountries.eu/data/mwi.svg', currency: 'Malawian kwacha', }, { name: 'Malaysia', capital: 'Kuala Lumpur', languages: ['Malaysian'], population: 31405416, flag: 'https://restcountries.eu/data/mys.svg', currency: 'Malaysian ringgit', }, { name: 'Maldives', capital: 'Malé', languages: ['Divehi'], population: 344023, flag: 'https://restcountries.eu/data/mdv.svg', currency: 'Maldivian rufiyaa', }, { name: 'Mali', capital: 'Bamako', languages: ['French'], population: 18135000, flag: 'https://restcountries.eu/data/mli.svg', currency: 'West African CFA franc', }, { name: 'Malta', capital: 'Valletta', languages: ['Maltese', 'English'], population: 425384, flag: 'https://restcountries.eu/data/mlt.svg', currency: 'Euro', }, { name: 'Marshall Islands', capital: 'Majuro', languages: ['English', 'Marshallese'], population: 54880, flag: 'https://restcountries.eu/data/mhl.svg', currency: 'United States dollar', }, { name: 'Martinique', capital: 'Fort-de-France', languages: ['French'], population: 378243, flag: 'https://restcountries.eu/data/mtq.svg', currency: 'Euro', }, { name: 'Mauritania', capital: 'Nouakchott', languages: ['Arabic'], population: 3718678, flag: 'https://restcountries.eu/data/mrt.svg', currency: 'Mauritanian ouguiya', }, { name: 'Mauritius', capital: 'Port Louis', languages: ['English'], population: 1262879, flag: 'https://restcountries.eu/data/mus.svg', currency: 'Mauritian rupee', }, { name: 'Mayotte', capital: 'Mamoudzou', languages: ['French'], population: 226915, flag: 'https://restcountries.eu/data/myt.svg', currency: 'Euro', }, { name: 'Mexico', capital: 'Mexico City', languages: ['Spanish'], population: 122273473, flag: 'https://restcountries.eu/data/mex.svg', currency: 'Mexican peso', }, { name: 'Micronesia (Federated States of)', capital: 'Palikir', languages: ['English'], population: 102800, flag: 'https://restcountries.eu/data/fsm.svg', currency: '[D]', }, { name: 'Moldova (Republic of)', capital: 'Chișinău', languages: ['Romanian'], population: 3553100, flag: 'https://restcountries.eu/data/mda.svg', currency: 'Moldovan leu', }, { name: 'Monaco', capital: 'Monaco', languages: ['French'], population: 38400, flag: 'https://restcountries.eu/data/mco.svg', currency: 'Euro', }, { name: 'Mongolia', capital: 'Ulan Bator', languages: ['Mongolian'], population: 3093100, flag: 'https://restcountries.eu/data/mng.svg', currency: 'Mongolian tögrög', }, { name: 'Montenegro', capital: 'Podgorica', languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], population: 621810, flag: 'https://restcountries.eu/data/mne.svg', currency: 'Euro', }, { name: 'Montserrat', capital: 'Plymouth', languages: ['English'], population: 4922, flag: 'https://restcountries.eu/data/msr.svg', currency: 'East Caribbean dollar', }, { name: 'Morocco', capital: 'Rabat', languages: ['Arabic'], population: 33337529, flag: 'https://restcountries.eu/data/mar.svg', currency: 'Moroccan dirham', }, { name: 'Mozambique', capital: 'Maputo', languages: ['Portuguese'], population: 26423700, flag: 'https://restcountries.eu/data/moz.svg', currency: 'Mozambican metical', }, { name: 'Myanmar', capital: 'Naypyidaw', languages: ['Burmese'], population: 51419420, flag: 'https://restcountries.eu/data/mmr.svg', currency: 'Burmese kyat', }, { name: 'Namibia', capital: 'Windhoek', languages: ['English', 'Afrikaans'], population: 2324388, flag: 'https://restcountries.eu/data/nam.svg', currency: 'Namibian dollar', }, { name: 'Nauru', capital: 'Yaren', languages: ['English', 'Nauruan'], population: 10084, flag: 'https://restcountries.eu/data/nru.svg', currency: 'Australian dollar', }, { name: 'Nepal', capital: 'Kathmandu', languages: ['Nepali'], population: 28431500, flag: 'https://restcountries.eu/data/npl.svg', currency: 'Nepalese rupee', }, { name: 'Netherlands', capital: 'Amsterdam', languages: ['Dutch'], population: 17019800, flag: 'https://restcountries.eu/data/nld.svg', currency: 'Euro', }, { name: 'New Caledonia', capital: 'Nouméa', languages: ['French'], population: 268767, flag: 'https://restcountries.eu/data/ncl.svg', currency: 'CFP franc', }, { name: 'New Zealand', capital: 'Wellington', languages: ['English', 'Māori'], population: 4697854, flag: 'https://restcountries.eu/data/nzl.svg', currency: 'New Zealand dollar', }, { name: 'Nicaragua', capital: 'Managua', languages: ['Spanish'], population: 6262703, flag: 'https://restcountries.eu/data/nic.svg', currency: 'Nicaraguan córdoba', }, { name: 'Niger', capital: 'Niamey', languages: ['French'], population: 20715000, flag: 'https://restcountries.eu/data/ner.svg', currency: 'West African CFA franc', }, { name: 'Nigeria', capital: 'Abuja', languages: ['English'], population: 186988000, flag: 'https://restcountries.eu/data/nga.svg', currency: 'Nigerian naira', }, { name: 'Niue', capital: 'Alofi', languages: ['English'], population: 1470, flag: 'https://restcountries.eu/data/niu.svg', currency: 'New Zealand dollar', }, { name: 'Norfolk Island', capital: 'Kingston', languages: ['English'], population: 2302, flag: 'https://restcountries.eu/data/nfk.svg', currency: 'Australian dollar', }, { name: "Korea (Democratic People's Republic of)", capital: 'Pyongyang', languages: ['Korean'], population: 25281000, flag: 'https://restcountries.eu/data/prk.svg', currency: 'North Korean won', }, { name: 'Northern Mariana Islands', capital: 'Saipan', languages: ['English', 'Chamorro'], population: 56940, flag: 'https://restcountries.eu/data/mnp.svg', currency: 'United States dollar', }, { name: 'Norway', capital: 'Oslo', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 5223256, flag: 'https://restcountries.eu/data/nor.svg', currency: 'Norwegian krone', }, { name: 'Oman', capital: 'Muscat', languages: ['Arabic'], population: 4420133, flag: 'https://restcountries.eu/data/omn.svg', currency: 'Omani rial', }, { name: 'Pakistan', capital: 'Islamabad', languages: ['English', 'Urdu'], population: 194125062, flag: 'https://restcountries.eu/data/pak.svg', currency: 'Pakistani rupee', }, { name: 'Palau', capital: 'Ngerulmud', languages: ['English'], population: 17950, flag: 'https://restcountries.eu/data/plw.svg', currency: '[E]', }, { name: 'Palestine, State of', capital: 'Ramallah', languages: ['Arabic'], population: 4682467, flag: 'https://restcountries.eu/data/pse.svg', currency: 'Israeli new sheqel', }, { name: 'Panama', capital: 'Panama City', languages: ['Spanish'], population: 3814672, flag: 'https://restcountries.eu/data/pan.svg', currency: 'Panamanian balboa', }, { name: 'Papua New Guinea', capital: 'Port Moresby', languages: ['English'], population: 8083700, flag: 'https://restcountries.eu/data/png.svg', currency: 'Papua New Guinean kina', }, { name: 'Paraguay', capital: 'Asunción', languages: ['Spanish', 'Guaraní'], population: 6854536, flag: 'https://restcountries.eu/data/pry.svg', currency: 'Paraguayan guaraní', }, { name: 'Peru', capital: 'Lima', languages: ['Spanish'], population: 31488700, flag: 'https://restcountries.eu/data/per.svg', currency: 'Peruvian sol', }, { name: 'Philippines', capital: 'Manila', languages: ['English'], population: 103279800, flag: 'https://restcountries.eu/data/phl.svg', currency: 'Philippine peso', }, { name: 'Pitcairn', capital: 'Adamstown', languages: ['English'], population: 56, flag: 'https://restcountries.eu/data/pcn.svg', currency: 'New Zealand dollar', }, { name: 'Poland', capital: 'Warsaw', languages: ['Polish'], population: 38437239, flag: 'https://restcountries.eu/data/pol.svg', currency: 'Polish złoty', }, { name: 'Portugal', capital: 'Lisbon', languages: ['Portuguese'], population: 10374822, flag: 'https://restcountries.eu/data/prt.svg', currency: 'Euro', }, { name: 'Puerto Rico', capital: 'San Juan', languages: ['Spanish', 'English'], population: 3474182, flag: 'https://restcountries.eu/data/pri.svg', currency: 'United States dollar', }, { name: 'Qatar', capital: 'Doha', languages: ['Arabic'], population: 2587564, flag: 'https://restcountries.eu/data/qat.svg', currency: 'Qatari riyal', }, { name: 'Republic of Kosovo', capital: 'Pristina', languages: ['Albanian', 'Serbian'], population: 1733842, flag: 'https://restcountries.eu/data/kos.svg', currency: 'Euro', }, { name: 'Réunion', capital: 'Saint-Denis', languages: ['French'], population: 840974, flag: 'https://restcountries.eu/data/reu.svg', currency: 'Euro', }, { name: 'Romania', capital: 'Bucharest', languages: ['Romanian'], population: 19861408, flag: 'https://restcountries.eu/data/rou.svg', currency: 'Romanian leu', }, { name: 'Russian Federation', capital: 'Moscow', languages: ['Russian'], population: 146599183, flag: 'https://restcountries.eu/data/rus.svg', currency: 'Russian ruble', }, { name: 'Rwanda', capital: 'Kigali', languages: ['Kinyarwanda', 'English', 'French'], population: 11553188, flag: 'https://restcountries.eu/data/rwa.svg', currency: 'Rwandan franc', }, { name: 'Saint Barthélemy', capital: 'Gustavia', languages: ['French'], population: 9417, flag: 'https://restcountries.eu/data/blm.svg', currency: 'Euro', }, { name: 'Saint Helena, Ascension and Tristan da Cunha', capital: 'Jamestown', languages: ['English'], population: 4255, flag: 'https://restcountries.eu/data/shn.svg', currency: 'Saint Helena pound', }, { name: 'Saint Kitts and Nevis', capital: 'Basseterre', languages: ['English'], population: 46204, flag: 'https://restcountries.eu/data/kna.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Lucia', capital: 'Castries', languages: ['English'], population: 186000, flag: 'https://restcountries.eu/data/lca.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Martin (French part)', capital: 'Marigot', languages: ['English', 'French', 'Dutch'], population: 36979, flag: 'https://restcountries.eu/data/maf.svg', currency: 'Euro', }, { name: 'Saint Pierre and Miquelon', capital: 'Saint-Pierre', languages: ['French'], population: 6069, flag: 'https://restcountries.eu/data/spm.svg', currency: 'Euro', }, { name: 'Saint Vincent and the Grenadines', capital: 'Kingstown', languages: ['English'], population: 109991, flag: 'https://restcountries.eu/data/vct.svg', currency: 'East Caribbean dollar', }, { name: 'Samoa', capital: 'Apia', languages: ['Samoan', 'English'], population: 194899, flag: 'https://restcountries.eu/data/wsm.svg', currency: 'Samoan tālā', }, { name: 'San Marino', capital: 'City of San Marino', languages: ['Italian'], population: 33005, flag: 'https://restcountries.eu/data/smr.svg', currency: 'Euro', }, { name: 'Sao Tome and Principe', capital: 'São Tomé', languages: ['Portuguese'], population: 187356, flag: 'https://restcountries.eu/data/stp.svg', currency: 'São Tomé and Príncipe dobra', }, { name: 'Saudi Arabia', capital: 'Riyadh', languages: ['Arabic'], population: 32248200, flag: 'https://restcountries.eu/data/sau.svg', currency: 'Saudi riyal', }, { name: 'Senegal', capital: 'Dakar', languages: ['French'], population: 14799859, flag: 'https://restcountries.eu/data/sen.svg', currency: 'West African CFA franc', }, { name: 'Serbia', capital: 'Belgrade', languages: ['Serbian'], population: 7076372, flag: 'https://restcountries.eu/data/srb.svg', currency: 'Serbian dinar', }, { name: 'Seychelles', capital: 'Victoria', languages: ['French', 'English'], population: 91400, flag: 'https://restcountries.eu/data/syc.svg', currency: 'Seychellois rupee', }, { name: 'Sierra Leone', capital: 'Freetown', languages: ['English'], population: 7075641, flag: 'https://restcountries.eu/data/sle.svg', currency: 'Sierra Leonean leone', }, { name: 'Singapore', capital: 'Singapore', languages: ['English', 'Malay', 'Tamil', 'Chinese'], population: 5535000, flag: 'https://restcountries.eu/data/sgp.svg', currency: 'Brunei dollar', }, { name: 'Sint Maarten (Dutch part)', capital: 'Philipsburg', languages: ['Dutch', 'English'], population: 38247, flag: 'https://restcountries.eu/data/sxm.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Slovakia', capital: 'Bratislava', languages: ['Slovak'], population: 5426252, flag: 'https://restcountries.eu/data/svk.svg', currency: 'Euro', }, { name: 'Slovenia', capital: 'Ljubljana', languages: ['Slovene'], population: 2064188, flag: 'https://restcountries.eu/data/svn.svg', currency: 'Euro', }, { name: 'Solomon Islands', capital: 'Honiara', languages: ['English'], population: 642000, flag: 'https://restcountries.eu/data/slb.svg', currency: 'Solomon Islands dollar', }, { name: 'Somalia', capital: 'Mogadishu', languages: ['Somali', 'Arabic'], population: 11079000, flag: 'https://restcountries.eu/data/som.svg', currency: 'Somali shilling', }, { name: 'South Africa', capital: 'Pretoria', languages: [ 'Afrikaans', 'English', 'Southern Ndebele', 'Southern Sotho', 'Swati', 'Tswana', 'Tsonga', 'Venda', 'Xhosa', 'Zulu', ], population: 55653654, flag: 'https://restcountries.eu/data/zaf.svg', currency: 'South African rand', }, { name: 'South Georgia and the South Sandwich Islands', capital: 'King Edward Point', languages: ['English'], population: 30, flag: 'https://restcountries.eu/data/sgs.svg', currency: 'British pound', }, { name: 'Korea (Republic of)', capital: 'Seoul', languages: ['Korean'], population: 50801405, flag: 'https://restcountries.eu/data/kor.svg', currency: 'South Korean won', }, { name: 'South Sudan', capital: 'Juba', languages: ['English'], population: 12131000, flag: 'https://restcountries.eu/data/ssd.svg', currency: 'South Sudanese pound', }, { name: 'Spain', capital: 'Madrid', languages: ['Spanish'], population: 46438422, flag: 'https://restcountries.eu/data/esp.svg', currency: 'Euro', }, { name: 'Sri Lanka', capital: 'Colombo', languages: ['Sinhalese', 'Tamil'], population: 20966000, flag: 'https://restcountries.eu/data/lka.svg', currency: 'Sri Lankan rupee', }, { name: 'Sudan', capital: 'Khartoum', languages: ['Arabic', 'English'], population: 39598700, flag: 'https://restcountries.eu/data/sdn.svg', currency: 'Sudanese pound', }, { name: 'Suriname', capital: 'Paramaribo', languages: ['Dutch'], population: 541638, flag: 'https://restcountries.eu/data/sur.svg', currency: 'Surinamese dollar', }, { name: 'Svalbard and Jan Mayen', capital: 'Longyearbyen', languages: ['Norwegian'], population: 2562, flag: 'https://restcountries.eu/data/sjm.svg', currency: 'Norwegian krone', }, { name: 'Swaziland', capital: 'Lobamba', languages: ['English', 'Swati'], population: 1132657, flag: 'https://restcountries.eu/data/swz.svg', currency: 'Swazi lilangeni', }, { name: 'Sweden', capital: 'Stockholm', languages: ['Swedish'], population: 9894888, flag: 'https://restcountries.eu/data/swe.svg', currency: 'Swedish krona', }, { name: 'Switzerland', capital: 'Bern', languages: ['German', 'French', 'Italian'], population: 8341600, flag: 'https://restcountries.eu/data/che.svg', currency: 'Swiss franc', }, { name: 'Syrian Arab Republic', capital: 'Damascus', languages: ['Arabic'], population: 18564000, flag: 'https://restcountries.eu/data/syr.svg', currency: 'Syrian pound', }, { name: 'Taiwan', capital: 'Taipei', languages: ['Chinese'], population: 23503349, flag: 'https://restcountries.eu/data/twn.svg', currency: 'New Taiwan dollar', }, { name: 'Tajikistan', capital: 'Dushanbe', languages: ['Tajik', 'Russian'], population: 8593600, flag: 'https://restcountries.eu/data/tjk.svg', currency: 'Tajikistani somoni', }, { name: 'Tanzania, United Republic of', capital: 'Dodoma', languages: ['Swahili', 'English'], population: 55155000, flag: 'https://restcountries.eu/data/tza.svg', currency: 'Tanzanian shilling', }, { name: 'Thailand', capital: 'Bangkok', languages: ['Thai'], population: 65327652, flag: 'https://restcountries.eu/data/tha.svg', currency: 'Thai baht', }, { name: 'Timor-Leste', capital: 'Dili', languages: ['Portuguese'], population: 1167242, flag: 'https://restcountries.eu/data/tls.svg', currency: 'United States dollar', }, { name: 'Togo', capital: 'Lomé', languages: ['French'], population: 7143000, flag: 'https://restcountries.eu/data/tgo.svg', currency: 'West African CFA franc', }, { name: 'Tokelau', capital: 'Fakaofo', languages: ['English'], population: 1411, flag: 'https://restcountries.eu/data/tkl.svg', currency: 'New Zealand dollar', }, { name: 'Tonga', capital: "Nuku'alofa", languages: ['English', 'Tonga (Tonga Islands)'], population: 103252, flag: 'https://restcountries.eu/data/ton.svg', currency: 'Tongan paʻanga', }, { name: 'Trinidad and Tobago', capital: 'Port of Spain', languages: ['English'], population: 1349667, flag: 'https://restcountries.eu/data/tto.svg', currency: 'Trinidad and Tobago dollar', }, { name: 'Tunisia', capital: 'Tunis', languages: ['Arabic'], population: 11154400, flag: 'https://restcountries.eu/data/tun.svg', currency: 'Tunisian dinar', }, { name: 'Turkey', capital: 'Ankara', languages: ['Turkish'], population: 78741053, flag: 'https://restcountries.eu/data/tur.svg', currency: 'Turkish lira', }, { name: 'Turkmenistan', capital: 'Ashgabat', languages: ['Turkmen', 'Russian'], population: 4751120, flag: 'https://restcountries.eu/data/tkm.svg', currency: 'Turkmenistan manat', }, { name: 'Turks and Caicos Islands', capital: 'Cockburn Town', languages: ['English'], population: 31458, flag: 'https://restcountries.eu/data/tca.svg', currency: 'United States dollar', }, { name: 'Tuvalu', capital: 'Funafuti', languages: ['English'], population: 10640, flag: 'https://restcountries.eu/data/tuv.svg', currency: 'Australian dollar', }, { name: 'Uganda', capital: 'Kampala', languages: ['English', 'Swahili'], population: 33860700, flag: 'https://restcountries.eu/data/uga.svg', currency: 'Ugandan shilling', }, { name: 'Ukraine', capital: 'Kiev', languages: ['Ukrainian'], population: 42692393, flag: 'https://restcountries.eu/data/ukr.svg', currency: 'Ukrainian hryvnia', }, { name: 'United Arab Emirates', capital: 'Abu Dhabi', languages: ['Arabic'], population: 9856000, flag: 'https://restcountries.eu/data/are.svg', currency: 'United Arab Emirates dirham', }, { name: 'United Kingdom of Great Britain and Northern Ireland', capital: 'London', languages: ['English'], population: 65110000, flag: 'https://restcountries.eu/data/gbr.svg', currency: 'British pound', }, { name: 'United States of America', capital: 'Washington, D.C.', languages: ['English'], population: 323947000, flag: 'https://restcountries.eu/data/usa.svg', currency: 'United States dollar', }, { name: 'Uruguay', capital: 'Montevideo', languages: ['Spanish'], population: 3480222, flag: 'https://restcountries.eu/data/ury.svg', currency: 'Uruguayan peso', }, { name: 'Uzbekistan', capital: 'Tashkent', languages: ['Uzbek', 'Russian'], population: 31576400, flag: 'https://restcountries.eu/data/uzb.svg', currency: "Uzbekistani so'm", }, { name: 'Vanuatu', capital: 'Port Vila', languages: ['Bislama', 'English', 'French'], population: 277500, flag: 'https://restcountries.eu/data/vut.svg', currency: 'Vanuatu vatu', }, { name: 'Venezuela (Bolivarian Republic of)', capital: 'Caracas', languages: ['Spanish'], population: 31028700, flag: 'https://restcountries.eu/data/ven.svg', currency: 'Venezuelan bolívar', }, { name: 'Viet Nam', capital: 'Hanoi', languages: ['Vietnamese'], population: 92700000, flag: 'https://restcountries.eu/data/vnm.svg', currency: 'Vietnamese đồng', }, { name: 'Wallis and Futuna', capital: 'Mata-Utu', languages: ['French'], population: 11750, flag: 'https://restcountries.eu/data/wlf.svg', currency: 'CFP franc', }, { name: 'Western Sahara', capital: 'El Aaiún', languages: ['Spanish'], population: 510713, flag: 'https://restcountries.eu/data/esh.svg', currency: 'Moroccan dirham', }, { name: 'Yemen', capital: "Sana'a", languages: ['Arabic'], population: 27478000, flag: 'https://restcountries.eu/data/yem.svg', currency: 'Yemeni rial', }, { name: 'Zambia', capital: 'Lusaka', languages: ['English'], population: 15933883, flag: 'https://restcountries.eu/data/zmb.svg', currency: 'Zambian kwacha', }, { name: 'Zimbabwe', capital: 'Harare', languages: ['English', 'Shona', 'Northern Ndebele'], population: 14240168, flag: 'https://restcountries.eu/data/zwe.svg', currency: 'Botswana pula', }, ] ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys_boilerplate/src/data/ten_most_highest_populations.js ================================================ export const tenHighestPopulation = [ { country: 'World', population: 7693165599 }, { country: 'China', population: 1377422166 }, { country: 'India', population: 1295210000 }, { country: 'United States of America', population: 323947000 }, { country: 'Indonesia', population: 258705000 }, { country: 'Brazil', population: 206135893 }, { country: 'Pakistan', population: 194125062 }, { country: 'Nigeria', population: 186988000 }, { country: 'Bangladesh', population: 161006790 }, { country: 'Russian Federation', population: 146599183 }, { country: 'Japan', population: 126960000 }, ] ================================================ FILE: 06_Day_Map_List_Keys/06_map_list_keys_boilerplate/src/index.js ================================================ import React from 'react' import ReactDOM from 'react-dom' // importing data import { countriesData } from './data/countries' import { tenMostHighestPopulations } from './data/ten_most_highest_populations' const countries = [ { name: 'Finland', city: 'Helsinki' }, { name: 'Sweden', city: 'Stockholm' }, { name: 'Denmark', city: 'Copenhagen' }, { name: 'Norway', city: 'Oslo' }, { name: 'Iceland', city: 'Reykjavík' }, ] // Country component const Country = ({ country: { name, city } }) => { return (

    {name}

    {city}
    ) } // countries component const Countries = ({ countries }) => { const countryList = countries.map((country) => ( )) return
    {countryList}
    } // The App, or the parent or the container component // Functional Component const App = () => { return (

    Countries List

    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ================================================ FILE: 07_Day_Class_Components/07_class_based_components_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 07_Day_Class_Components/07_class_based_components_boilerplate/README.md ================================================ # 30 Days of React App: Day 7 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 07_Day_Class_Components/07_class_based_components_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 07_Day_Class_Components/07_class_based_components_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 07_Day_Class_Components/07_class_based_components_boilerplate/src/data/countries.js ================================================ export const countriesData = [ { name: 'Afghanistan', capital: 'Kabul', languages: ['Pashto', 'Uzbek', 'Turkmen'], population: 27657145, flag: 'https://restcountries.eu/data/afg.svg', currency: 'Afghan afghani', }, { name: 'Åland Islands', capital: 'Mariehamn', languages: ['Swedish'], population: 28875, flag: 'https://restcountries.eu/data/ala.svg', currency: 'Euro', }, { name: 'Albania', capital: 'Tirana', languages: ['Albanian'], population: 2886026, flag: 'https://restcountries.eu/data/alb.svg', currency: 'Albanian lek', }, { name: 'Algeria', capital: 'Algiers', languages: ['Arabic'], population: 40400000, flag: 'https://restcountries.eu/data/dza.svg', currency: 'Algerian dinar', }, { name: 'American Samoa', capital: 'Pago Pago', languages: ['English', 'Samoan'], population: 57100, flag: 'https://restcountries.eu/data/asm.svg', currency: 'United State Dollar', }, { name: 'Andorra', capital: 'Andorra la Vella', languages: ['Catalan'], population: 78014, flag: 'https://restcountries.eu/data/and.svg', currency: 'Euro', }, { name: 'Angola', capital: 'Luanda', languages: ['Portuguese'], population: 25868000, flag: 'https://restcountries.eu/data/ago.svg', currency: 'Angolan kwanza', }, { name: 'Anguilla', capital: 'The Valley', languages: ['English'], population: 13452, flag: 'https://restcountries.eu/data/aia.svg', currency: 'East Caribbean dollar', }, { name: 'Antarctica', capital: '', languages: ['English', 'Russian'], population: 1000, flag: 'https://restcountries.eu/data/ata.svg', currency: 'Australian dollar', }, { name: 'Antigua and Barbuda', capital: "Saint John's", languages: ['English'], population: 86295, flag: 'https://restcountries.eu/data/atg.svg', currency: 'East Caribbean dollar', }, { name: 'Argentina', capital: 'Buenos Aires', languages: ['Spanish', 'Guaraní'], population: 43590400, flag: 'https://restcountries.eu/data/arg.svg', currency: 'Argentine peso', }, { name: 'Armenia', capital: 'Yerevan', languages: ['Armenian', 'Russian'], population: 2994400, flag: 'https://restcountries.eu/data/arm.svg', currency: 'Armenian dram', }, { name: 'Aruba', capital: 'Oranjestad', languages: ['Dutch', '(Eastern) Punjabi'], population: 107394, flag: 'https://restcountries.eu/data/abw.svg', currency: 'Aruban florin', }, { name: 'Australia', capital: 'Canberra', languages: ['English'], population: 24117360, flag: 'https://restcountries.eu/data/aus.svg', currency: 'Australian dollar', }, { name: 'Austria', capital: 'Vienna', languages: ['German'], population: 8725931, flag: 'https://restcountries.eu/data/aut.svg', currency: 'Euro', }, { name: 'Azerbaijan', capital: 'Baku', languages: ['Azerbaijani'], population: 9730500, flag: 'https://restcountries.eu/data/aze.svg', currency: 'Azerbaijani manat', }, { name: 'Bahamas', capital: 'Nassau', languages: ['English'], population: 378040, flag: 'https://restcountries.eu/data/bhs.svg', currency: 'Bahamian dollar', }, { name: 'Bahrain', capital: 'Manama', languages: ['Arabic'], population: 1404900, flag: 'https://restcountries.eu/data/bhr.svg', currency: 'Bahraini dinar', }, { name: 'Bangladesh', capital: 'Dhaka', languages: ['Bengali'], population: 161006790, flag: 'https://restcountries.eu/data/bgd.svg', currency: 'Bangladeshi taka', }, { name: 'Barbados', capital: 'Bridgetown', languages: ['English'], population: 285000, flag: 'https://restcountries.eu/data/brb.svg', currency: 'Barbadian dollar', }, { name: 'Belarus', capital: 'Minsk', languages: ['Belarusian', 'Russian'], population: 9498700, flag: 'https://restcountries.eu/data/blr.svg', currency: 'New Belarusian ruble', }, { name: 'Belgium', capital: 'Brussels', languages: ['Dutch', 'French', 'German'], population: 11319511, flag: 'https://restcountries.eu/data/bel.svg', currency: 'Euro', }, { name: 'Belize', capital: 'Belmopan', languages: ['English', 'Spanish'], population: 370300, flag: 'https://restcountries.eu/data/blz.svg', currency: 'Belize dollar', }, { name: 'Benin', capital: 'Porto-Novo', languages: ['French'], population: 10653654, flag: 'https://restcountries.eu/data/ben.svg', currency: 'West African CFA franc', }, { name: 'Bermuda', capital: 'Hamilton', languages: ['English'], population: 61954, flag: 'https://restcountries.eu/data/bmu.svg', currency: 'Bermudian dollar', }, { name: 'Bhutan', capital: 'Thimphu', languages: ['Dzongkha'], population: 775620, flag: 'https://restcountries.eu/data/btn.svg', currency: 'Bhutanese ngultrum', }, { name: 'Bolivia (Plurinational State of)', capital: 'Sucre', languages: ['Spanish', 'Aymara', 'Quechua'], population: 10985059, flag: 'https://restcountries.eu/data/bol.svg', currency: 'Bolivian boliviano', }, { name: 'Bonaire, Sint Eustatius and Saba', capital: 'Kralendijk', languages: ['Dutch'], population: 17408, flag: 'https://restcountries.eu/data/bes.svg', currency: 'United States dollar', }, { name: 'Bosnia and Herzegovina', capital: 'Sarajevo', languages: ['Bosnian', 'Croatian', 'Serbian'], population: 3531159, flag: 'https://restcountries.eu/data/bih.svg', currency: 'Bosnia and Herzegovina convertible mark', }, { name: 'Botswana', capital: 'Gaborone', languages: ['English', 'Tswana'], population: 2141206, flag: 'https://restcountries.eu/data/bwa.svg', currency: 'Botswana pula', }, { name: 'Bouvet Island', capital: '', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 0, flag: 'https://restcountries.eu/data/bvt.svg', currency: 'Norwegian krone', }, { name: 'Brazil', capital: 'Brasília', languages: ['Portuguese'], population: 206135893, flag: 'https://restcountries.eu/data/bra.svg', currency: 'Brazilian real', }, { name: 'British Indian Ocean Territory', capital: 'Diego Garcia', languages: ['English'], population: 3000, flag: 'https://restcountries.eu/data/iot.svg', currency: 'United States dollar', }, { name: 'United States Minor Outlying Islands', capital: '', languages: ['English'], population: 300, flag: 'https://restcountries.eu/data/umi.svg', currency: 'United States Dollar', }, { name: 'Virgin Islands (British)', capital: 'Road Town', languages: ['English'], population: 28514, flag: 'https://restcountries.eu/data/vgb.svg', currency: '[D]', }, { name: 'Virgin Islands (U.S.)', capital: 'Charlotte Amalie', languages: ['English'], population: 114743, flag: 'https://restcountries.eu/data/vir.svg', currency: 'United States dollar', }, { name: 'Brunei Darussalam', capital: 'Bandar Seri Begawan', languages: ['Malay'], population: 411900, flag: 'https://restcountries.eu/data/brn.svg', currency: 'Brunei dollar', }, { name: 'Bulgaria', capital: 'Sofia', languages: ['Bulgarian'], population: 7153784, flag: 'https://restcountries.eu/data/bgr.svg', currency: 'Bulgarian lev', }, { name: 'Burkina Faso', capital: 'Ouagadougou', languages: ['French', 'Fula'], population: 19034397, flag: 'https://restcountries.eu/data/bfa.svg', currency: 'West African CFA franc', }, { name: 'Burundi', capital: 'Bujumbura', languages: ['French', 'Kirundi'], population: 10114505, flag: 'https://restcountries.eu/data/bdi.svg', currency: 'Burundian franc', }, { name: 'Cambodia', capital: 'Phnom Penh', languages: ['Khmer'], population: 15626444, flag: 'https://restcountries.eu/data/khm.svg', currency: 'Cambodian riel', }, { name: 'Cameroon', capital: 'Yaoundé', languages: ['English', 'French'], population: 22709892, flag: 'https://restcountries.eu/data/cmr.svg', currency: 'Central African CFA franc', }, { name: 'Canada', capital: 'Ottawa', languages: ['English', 'French'], population: 36155487, flag: 'https://restcountries.eu/data/can.svg', currency: 'Canadian dollar', }, { name: 'Cabo Verde', capital: 'Praia', languages: ['Portuguese'], population: 531239, flag: 'https://restcountries.eu/data/cpv.svg', currency: 'Cape Verdean escudo', }, { name: 'Cayman Islands', capital: 'George Town', languages: ['English'], population: 58238, flag: 'https://restcountries.eu/data/cym.svg', currency: 'Cayman Islands dollar', }, { name: 'Central African Republic', capital: 'Bangui', languages: ['French', 'Sango'], population: 4998000, flag: 'https://restcountries.eu/data/caf.svg', currency: 'Central African CFA franc', }, { name: 'Chad', capital: "N'Djamena", languages: ['French', 'Arabic'], population: 14497000, flag: 'https://restcountries.eu/data/tcd.svg', currency: 'Central African CFA franc', }, { name: 'Chile', capital: 'Santiago', languages: ['Spanish'], population: 18191900, flag: 'https://restcountries.eu/data/chl.svg', currency: 'Chilean peso', }, { name: 'China', capital: 'Beijing', languages: ['Chinese'], population: 1377422166, flag: 'https://restcountries.eu/data/chn.svg', currency: 'Chinese yuan', }, { name: 'Christmas Island', capital: 'Flying Fish Cove', languages: ['English'], population: 2072, flag: 'https://restcountries.eu/data/cxr.svg', currency: 'Australian dollar', }, { name: 'Cocos (Keeling) Islands', capital: 'West Island', languages: ['English'], population: 550, flag: 'https://restcountries.eu/data/cck.svg', currency: 'Australian dollar', }, { name: 'Colombia', capital: 'Bogotá', languages: ['Spanish'], population: 48759958, flag: 'https://restcountries.eu/data/col.svg', currency: 'Colombian peso', }, { name: 'Comoros', capital: 'Moroni', languages: ['Arabic', 'French'], population: 806153, flag: 'https://restcountries.eu/data/com.svg', currency: 'Comorian franc', }, { name: 'Congo', capital: 'Brazzaville', languages: ['French', 'Lingala'], population: 4741000, flag: 'https://restcountries.eu/data/cog.svg', currency: 'Central African CFA franc', }, { name: 'Congo (Democratic Republic of the)', capital: 'Kinshasa', languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], population: 85026000, flag: 'https://restcountries.eu/data/cod.svg', currency: 'Congolese franc', }, { name: 'Cook Islands', capital: 'Avarua', languages: ['English'], population: 18100, flag: 'https://restcountries.eu/data/cok.svg', currency: 'New Zealand dollar', }, { name: 'Costa Rica', capital: 'San José', languages: ['Spanish'], population: 4890379, flag: 'https://restcountries.eu/data/cri.svg', currency: 'Costa Rican colón', }, { name: 'Croatia', capital: 'Zagreb', languages: ['Croatian'], population: 4190669, flag: 'https://restcountries.eu/data/hrv.svg', currency: 'Croatian kuna', }, { name: 'Cuba', capital: 'Havana', languages: ['Spanish'], population: 11239004, flag: 'https://restcountries.eu/data/cub.svg', currency: 'Cuban convertible peso', }, { name: 'Curaçao', capital: 'Willemstad', languages: ['Dutch', '(Eastern) Punjabi', 'English'], population: 154843, flag: 'https://restcountries.eu/data/cuw.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Cyprus', capital: 'Nicosia', languages: ['Greek (modern)', 'Turkish', 'Armenian'], population: 847000, flag: 'https://restcountries.eu/data/cyp.svg', currency: 'Euro', }, { name: 'Czech Republic', capital: 'Prague', languages: ['Czech', 'Slovak'], population: 10558524, flag: 'https://restcountries.eu/data/cze.svg', currency: 'Czech koruna', }, { name: 'Denmark', capital: 'Copenhagen', languages: ['Danish'], population: 5717014, flag: 'https://restcountries.eu/data/dnk.svg', currency: 'Danish krone', }, { name: 'Djibouti', capital: 'Djibouti', languages: ['French', 'Arabic'], population: 900000, flag: 'https://restcountries.eu/data/dji.svg', currency: 'Djiboutian franc', }, { name: 'Dominica', capital: 'Roseau', languages: ['English'], population: 71293, flag: 'https://restcountries.eu/data/dma.svg', currency: 'East Caribbean dollar', }, { name: 'Dominican Republic', capital: 'Santo Domingo', languages: ['Spanish'], population: 10075045, flag: 'https://restcountries.eu/data/dom.svg', currency: 'Dominican peso', }, { name: 'Ecuador', capital: 'Quito', languages: ['Spanish'], population: 16545799, flag: 'https://restcountries.eu/data/ecu.svg', currency: 'United States dollar', }, { name: 'Egypt', capital: 'Cairo', languages: ['Arabic'], population: 91290000, flag: 'https://restcountries.eu/data/egy.svg', currency: 'Egyptian pound', }, { name: 'El Salvador', capital: 'San Salvador', languages: ['Spanish'], population: 6520675, flag: 'https://restcountries.eu/data/slv.svg', currency: 'United States dollar', }, { name: 'Equatorial Guinea', capital: 'Malabo', languages: ['Spanish', 'French'], population: 1222442, flag: 'https://restcountries.eu/data/gnq.svg', currency: 'Central African CFA franc', }, { name: 'Eritrea', capital: 'Asmara', languages: ['Tigrinya', 'Arabic', 'English'], population: 5352000, flag: 'https://restcountries.eu/data/eri.svg', currency: 'Eritrean nakfa', }, { name: 'Estonia', capital: 'Tallinn', languages: ['Estonian'], population: 1315944, flag: 'https://restcountries.eu/data/est.svg', currency: 'Euro', }, { name: 'Ethiopia', capital: 'Addis Ababa', languages: ['Amharic'], population: 92206005, flag: 'https://restcountries.eu/data/eth.svg', currency: 'Ethiopian birr', }, { name: 'Falkland Islands (Malvinas)', capital: 'Stanley', languages: ['English'], population: 2563, flag: 'https://restcountries.eu/data/flk.svg', currency: 'Falkland Islands pound', }, { name: 'Faroe Islands', capital: 'Tórshavn', languages: ['Faroese'], population: 49376, flag: 'https://restcountries.eu/data/fro.svg', currency: 'Danish krone', }, { name: 'Fiji', capital: 'Suva', languages: ['English', 'Fijian', 'Hindi', 'Urdu'], population: 867000, flag: 'https://restcountries.eu/data/fji.svg', currency: 'Fijian dollar', }, { name: 'Finland', capital: 'Helsinki', languages: ['Finnish', 'Swedish'], population: 5491817, flag: 'https://restcountries.eu/data/fin.svg', currency: 'Euro', }, { name: 'France', capital: 'Paris', languages: ['French'], population: 66710000, flag: 'https://restcountries.eu/data/fra.svg', currency: 'Euro', }, { name: 'French Guiana', capital: 'Cayenne', languages: ['French'], population: 254541, flag: 'https://restcountries.eu/data/guf.svg', currency: 'Euro', }, { name: 'French Polynesia', capital: 'Papeetē', languages: ['French'], population: 271800, flag: 'https://restcountries.eu/data/pyf.svg', currency: 'CFP franc', }, { name: 'French Southern Territories', capital: 'Port-aux-Français', languages: ['French'], population: 140, flag: 'https://restcountries.eu/data/atf.svg', currency: 'Euro', }, { name: 'Gabon', capital: 'Libreville', languages: ['French'], population: 1802278, flag: 'https://restcountries.eu/data/gab.svg', currency: 'Central African CFA franc', }, { name: 'Gambia', capital: 'Banjul', languages: ['English'], population: 1882450, flag: 'https://restcountries.eu/data/gmb.svg', currency: 'Gambian dalasi', }, { name: 'Georgia', capital: 'Tbilisi', languages: ['Georgian'], population: 3720400, flag: 'https://restcountries.eu/data/geo.svg', currency: 'Georgian Lari', }, { name: 'Germany', capital: 'Berlin', languages: ['German'], population: 81770900, flag: 'https://restcountries.eu/data/deu.svg', currency: 'Euro', }, { name: 'Ghana', capital: 'Accra', languages: ['English'], population: 27670174, flag: 'https://restcountries.eu/data/gha.svg', currency: 'Ghanaian cedi', }, { name: 'Gibraltar', capital: 'Gibraltar', languages: ['English'], population: 33140, flag: 'https://restcountries.eu/data/gib.svg', currency: 'Gibraltar pound', }, { name: 'Greece', capital: 'Athens', languages: ['Greek (modern)'], population: 10858018, flag: 'https://restcountries.eu/data/grc.svg', currency: 'Euro', }, { name: 'Greenland', capital: 'Nuuk', languages: ['Kalaallisut'], population: 55847, flag: 'https://restcountries.eu/data/grl.svg', currency: 'Danish krone', }, { name: 'Grenada', capital: "St. George's", languages: ['English'], population: 103328, flag: 'https://restcountries.eu/data/grd.svg', currency: 'East Caribbean dollar', }, { name: 'Guadeloupe', capital: 'Basse-Terre', languages: ['French'], population: 400132, flag: 'https://restcountries.eu/data/glp.svg', currency: 'Euro', }, { name: 'Guam', capital: 'Hagåtña', languages: ['English', 'Chamorro', 'Spanish'], population: 184200, flag: 'https://restcountries.eu/data/gum.svg', currency: 'United States dollar', }, { name: 'Guatemala', capital: 'Guatemala City', languages: ['Spanish'], population: 16176133, flag: 'https://restcountries.eu/data/gtm.svg', currency: 'Guatemalan quetzal', }, { name: 'Guernsey', capital: 'St. Peter Port', languages: ['English', 'French'], population: 62999, flag: 'https://restcountries.eu/data/ggy.svg', currency: 'British pound', }, { name: 'Guinea', capital: 'Conakry', languages: ['French', 'Fula'], population: 12947000, flag: 'https://restcountries.eu/data/gin.svg', currency: 'Guinean franc', }, { name: 'Guinea-Bissau', capital: 'Bissau', languages: ['Portuguese'], population: 1547777, flag: 'https://restcountries.eu/data/gnb.svg', currency: 'West African CFA franc', }, { name: 'Guyana', capital: 'Georgetown', languages: ['English'], population: 746900, flag: 'https://restcountries.eu/data/guy.svg', currency: 'Guyanese dollar', }, { name: 'Haiti', capital: 'Port-au-Prince', languages: ['French', 'Haitian'], population: 11078033, flag: 'https://restcountries.eu/data/hti.svg', currency: 'Haitian gourde', }, { name: 'Heard Island and McDonald Islands', capital: '', languages: ['English'], population: 0, flag: 'https://restcountries.eu/data/hmd.svg', currency: 'Australian dollar', }, { name: 'Holy See', capital: 'Rome', languages: ['Latin', 'Italian', 'French', 'German'], population: 451, flag: 'https://restcountries.eu/data/vat.svg', currency: 'Euro', }, { name: 'Honduras', capital: 'Tegucigalpa', languages: ['Spanish'], population: 8576532, flag: 'https://restcountries.eu/data/hnd.svg', currency: 'Honduran lempira', }, { name: 'Hong Kong', capital: 'City of Victoria', languages: ['English', 'Chinese'], population: 7324300, flag: 'https://restcountries.eu/data/hkg.svg', currency: 'Hong Kong dollar', }, { name: 'Hungary', capital: 'Budapest', languages: ['Hungarian'], population: 9823000, flag: 'https://restcountries.eu/data/hun.svg', currency: 'Hungarian forint', }, { name: 'Iceland', capital: 'Reykjavík', languages: ['Icelandic'], population: 334300, flag: 'https://restcountries.eu/data/isl.svg', currency: 'Icelandic króna', }, { name: 'India', capital: 'New Delhi', languages: ['Hindi', 'English'], population: 1295210000, flag: 'https://restcountries.eu/data/ind.svg', currency: 'Indian rupee', }, { name: 'Indonesia', capital: 'Jakarta', languages: ['Indonesian'], population: 258705000, flag: 'https://restcountries.eu/data/idn.svg', currency: 'Indonesian rupiah', }, { name: "Côte d'Ivoire", capital: 'Yamoussoukro', languages: ['French'], population: 22671331, flag: 'https://restcountries.eu/data/civ.svg', currency: 'West African CFA franc', }, { name: 'Iran (Islamic Republic of)', capital: 'Tehran', languages: ['Persian (Farsi)'], population: 79369900, flag: 'https://restcountries.eu/data/irn.svg', currency: 'Iranian rial', }, { name: 'Iraq', capital: 'Baghdad', languages: ['Arabic', 'Kurdish'], population: 37883543, flag: 'https://restcountries.eu/data/irq.svg', currency: 'Iraqi dinar', }, { name: 'Ireland', capital: 'Dublin', languages: ['Irish', 'English'], population: 6378000, flag: 'https://restcountries.eu/data/irl.svg', currency: 'Euro', }, { name: 'Isle of Man', capital: 'Douglas', languages: ['English', 'Manx'], population: 84497, flag: 'https://restcountries.eu/data/imn.svg', currency: 'British pound', }, { name: 'Israel', capital: 'Jerusalem', languages: ['Hebrew (modern)', 'Arabic'], population: 8527400, flag: 'https://restcountries.eu/data/isr.svg', currency: 'Israeli new shekel', }, { name: 'Italy', capital: 'Rome', languages: ['Italian'], population: 60665551, flag: 'https://restcountries.eu/data/ita.svg', currency: 'Euro', }, { name: 'Jamaica', capital: 'Kingston', languages: ['English'], population: 2723246, flag: 'https://restcountries.eu/data/jam.svg', currency: 'Jamaican dollar', }, { name: 'Japan', capital: 'Tokyo', languages: ['Japanese'], population: 126960000, flag: 'https://restcountries.eu/data/jpn.svg', currency: 'Japanese yen', }, { name: 'Jersey', capital: 'Saint Helier', languages: ['English', 'French'], population: 100800, flag: 'https://restcountries.eu/data/jey.svg', currency: 'British pound', }, { name: 'Jordan', capital: 'Amman', languages: ['Arabic'], population: 9531712, flag: 'https://restcountries.eu/data/jor.svg', currency: 'Jordanian dinar', }, { name: 'Kazakhstan', capital: 'Astana', languages: ['Kazakh', 'Russian'], population: 17753200, flag: 'https://restcountries.eu/data/kaz.svg', currency: 'Kazakhstani tenge', }, { name: 'Kenya', capital: 'Nairobi', languages: ['English', 'Swahili'], population: 47251000, flag: 'https://restcountries.eu/data/ken.svg', currency: 'Kenyan shilling', }, { name: 'Kiribati', capital: 'South Tarawa', languages: ['English'], population: 113400, flag: 'https://restcountries.eu/data/kir.svg', currency: 'Australian dollar', }, { name: 'Kuwait', capital: 'Kuwait City', languages: ['Arabic'], population: 4183658, flag: 'https://restcountries.eu/data/kwt.svg', currency: 'Kuwaiti dinar', }, { name: 'Kyrgyzstan', capital: 'Bishkek', languages: ['Kyrgyz', 'Russian'], population: 6047800, flag: 'https://restcountries.eu/data/kgz.svg', currency: 'Kyrgyzstani som', }, { name: "Lao People's Democratic Republic", capital: 'Vientiane', languages: ['Lao'], population: 6492400, flag: 'https://restcountries.eu/data/lao.svg', currency: 'Lao kip', }, { name: 'Latvia', capital: 'Riga', languages: ['Latvian'], population: 1961600, flag: 'https://restcountries.eu/data/lva.svg', currency: 'Euro', }, { name: 'Lebanon', capital: 'Beirut', languages: ['Arabic', 'French'], population: 5988000, flag: 'https://restcountries.eu/data/lbn.svg', currency: 'Lebanese pound', }, { name: 'Lesotho', capital: 'Maseru', languages: ['English', 'Southern Sotho'], population: 1894194, flag: 'https://restcountries.eu/data/lso.svg', currency: 'Lesotho loti', }, { name: 'Liberia', capital: 'Monrovia', languages: ['English'], population: 4615000, flag: 'https://restcountries.eu/data/lbr.svg', currency: 'Liberian dollar', }, { name: 'Libya', capital: 'Tripoli', languages: ['Arabic'], population: 6385000, flag: 'https://restcountries.eu/data/lby.svg', currency: 'Libyan dinar', }, { name: 'Liechtenstein', capital: 'Vaduz', languages: ['German'], population: 37623, flag: 'https://restcountries.eu/data/lie.svg', currency: 'Swiss franc', }, { name: 'Lithuania', capital: 'Vilnius', languages: ['Lithuanian'], population: 2872294, flag: 'https://restcountries.eu/data/ltu.svg', currency: 'Euro', }, { name: 'Luxembourg', capital: 'Luxembourg', languages: ['French', 'German', 'Luxembourgish'], population: 576200, flag: 'https://restcountries.eu/data/lux.svg', currency: 'Euro', }, { name: 'Macao', capital: '', languages: ['Chinese', 'Portuguese'], population: 649100, flag: 'https://restcountries.eu/data/mac.svg', currency: 'Macanese pataca', }, { name: 'Macedonia (the former Yugoslav Republic of)', capital: 'Skopje', languages: ['Macedonian'], population: 2058539, flag: 'https://restcountries.eu/data/mkd.svg', currency: 'Macedonian denar', }, { name: 'Madagascar', capital: 'Antananarivo', languages: ['French', 'Malagasy'], population: 22434363, flag: 'https://restcountries.eu/data/mdg.svg', currency: 'Malagasy ariary', }, { name: 'Malawi', capital: 'Lilongwe', languages: ['English', 'Chichewa'], population: 16832910, flag: 'https://restcountries.eu/data/mwi.svg', currency: 'Malawian kwacha', }, { name: 'Malaysia', capital: 'Kuala Lumpur', languages: ['Malaysian'], population: 31405416, flag: 'https://restcountries.eu/data/mys.svg', currency: 'Malaysian ringgit', }, { name: 'Maldives', capital: 'Malé', languages: ['Divehi'], population: 344023, flag: 'https://restcountries.eu/data/mdv.svg', currency: 'Maldivian rufiyaa', }, { name: 'Mali', capital: 'Bamako', languages: ['French'], population: 18135000, flag: 'https://restcountries.eu/data/mli.svg', currency: 'West African CFA franc', }, { name: 'Malta', capital: 'Valletta', languages: ['Maltese', 'English'], population: 425384, flag: 'https://restcountries.eu/data/mlt.svg', currency: 'Euro', }, { name: 'Marshall Islands', capital: 'Majuro', languages: ['English', 'Marshallese'], population: 54880, flag: 'https://restcountries.eu/data/mhl.svg', currency: 'United States dollar', }, { name: 'Martinique', capital: 'Fort-de-France', languages: ['French'], population: 378243, flag: 'https://restcountries.eu/data/mtq.svg', currency: 'Euro', }, { name: 'Mauritania', capital: 'Nouakchott', languages: ['Arabic'], population: 3718678, flag: 'https://restcountries.eu/data/mrt.svg', currency: 'Mauritanian ouguiya', }, { name: 'Mauritius', capital: 'Port Louis', languages: ['English'], population: 1262879, flag: 'https://restcountries.eu/data/mus.svg', currency: 'Mauritian rupee', }, { name: 'Mayotte', capital: 'Mamoudzou', languages: ['French'], population: 226915, flag: 'https://restcountries.eu/data/myt.svg', currency: 'Euro', }, { name: 'Mexico', capital: 'Mexico City', languages: ['Spanish'], population: 122273473, flag: 'https://restcountries.eu/data/mex.svg', currency: 'Mexican peso', }, { name: 'Micronesia (Federated States of)', capital: 'Palikir', languages: ['English'], population: 102800, flag: 'https://restcountries.eu/data/fsm.svg', currency: '[D]', }, { name: 'Moldova (Republic of)', capital: 'Chișinău', languages: ['Romanian'], population: 3553100, flag: 'https://restcountries.eu/data/mda.svg', currency: 'Moldovan leu', }, { name: 'Monaco', capital: 'Monaco', languages: ['French'], population: 38400, flag: 'https://restcountries.eu/data/mco.svg', currency: 'Euro', }, { name: 'Mongolia', capital: 'Ulan Bator', languages: ['Mongolian'], population: 3093100, flag: 'https://restcountries.eu/data/mng.svg', currency: 'Mongolian tögrög', }, { name: 'Montenegro', capital: 'Podgorica', languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], population: 621810, flag: 'https://restcountries.eu/data/mne.svg', currency: 'Euro', }, { name: 'Montserrat', capital: 'Plymouth', languages: ['English'], population: 4922, flag: 'https://restcountries.eu/data/msr.svg', currency: 'East Caribbean dollar', }, { name: 'Morocco', capital: 'Rabat', languages: ['Arabic'], population: 33337529, flag: 'https://restcountries.eu/data/mar.svg', currency: 'Moroccan dirham', }, { name: 'Mozambique', capital: 'Maputo', languages: ['Portuguese'], population: 26423700, flag: 'https://restcountries.eu/data/moz.svg', currency: 'Mozambican metical', }, { name: 'Myanmar', capital: 'Naypyidaw', languages: ['Burmese'], population: 51419420, flag: 'https://restcountries.eu/data/mmr.svg', currency: 'Burmese kyat', }, { name: 'Namibia', capital: 'Windhoek', languages: ['English', 'Afrikaans'], population: 2324388, flag: 'https://restcountries.eu/data/nam.svg', currency: 'Namibian dollar', }, { name: 'Nauru', capital: 'Yaren', languages: ['English', 'Nauruan'], population: 10084, flag: 'https://restcountries.eu/data/nru.svg', currency: 'Australian dollar', }, { name: 'Nepal', capital: 'Kathmandu', languages: ['Nepali'], population: 28431500, flag: 'https://restcountries.eu/data/npl.svg', currency: 'Nepalese rupee', }, { name: 'Netherlands', capital: 'Amsterdam', languages: ['Dutch'], population: 17019800, flag: 'https://restcountries.eu/data/nld.svg', currency: 'Euro', }, { name: 'New Caledonia', capital: 'Nouméa', languages: ['French'], population: 268767, flag: 'https://restcountries.eu/data/ncl.svg', currency: 'CFP franc', }, { name: 'New Zealand', capital: 'Wellington', languages: ['English', 'Māori'], population: 4697854, flag: 'https://restcountries.eu/data/nzl.svg', currency: 'New Zealand dollar', }, { name: 'Nicaragua', capital: 'Managua', languages: ['Spanish'], population: 6262703, flag: 'https://restcountries.eu/data/nic.svg', currency: 'Nicaraguan córdoba', }, { name: 'Niger', capital: 'Niamey', languages: ['French'], population: 20715000, flag: 'https://restcountries.eu/data/ner.svg', currency: 'West African CFA franc', }, { name: 'Nigeria', capital: 'Abuja', languages: ['English'], population: 186988000, flag: 'https://restcountries.eu/data/nga.svg', currency: 'Nigerian naira', }, { name: 'Niue', capital: 'Alofi', languages: ['English'], population: 1470, flag: 'https://restcountries.eu/data/niu.svg', currency: 'New Zealand dollar', }, { name: 'Norfolk Island', capital: 'Kingston', languages: ['English'], population: 2302, flag: 'https://restcountries.eu/data/nfk.svg', currency: 'Australian dollar', }, { name: "Korea (Democratic People's Republic of)", capital: 'Pyongyang', languages: ['Korean'], population: 25281000, flag: 'https://restcountries.eu/data/prk.svg', currency: 'North Korean won', }, { name: 'Northern Mariana Islands', capital: 'Saipan', languages: ['English', 'Chamorro'], population: 56940, flag: 'https://restcountries.eu/data/mnp.svg', currency: 'United States dollar', }, { name: 'Norway', capital: 'Oslo', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 5223256, flag: 'https://restcountries.eu/data/nor.svg', currency: 'Norwegian krone', }, { name: 'Oman', capital: 'Muscat', languages: ['Arabic'], population: 4420133, flag: 'https://restcountries.eu/data/omn.svg', currency: 'Omani rial', }, { name: 'Pakistan', capital: 'Islamabad', languages: ['English', 'Urdu'], population: 194125062, flag: 'https://restcountries.eu/data/pak.svg', currency: 'Pakistani rupee', }, { name: 'Palau', capital: 'Ngerulmud', languages: ['English'], population: 17950, flag: 'https://restcountries.eu/data/plw.svg', currency: '[E]', }, { name: 'Palestine, State of', capital: 'Ramallah', languages: ['Arabic'], population: 4682467, flag: 'https://restcountries.eu/data/pse.svg', currency: 'Israeli new sheqel', }, { name: 'Panama', capital: 'Panama City', languages: ['Spanish'], population: 3814672, flag: 'https://restcountries.eu/data/pan.svg', currency: 'Panamanian balboa', }, { name: 'Papua New Guinea', capital: 'Port Moresby', languages: ['English'], population: 8083700, flag: 'https://restcountries.eu/data/png.svg', currency: 'Papua New Guinean kina', }, { name: 'Paraguay', capital: 'Asunción', languages: ['Spanish', 'Guaraní'], population: 6854536, flag: 'https://restcountries.eu/data/pry.svg', currency: 'Paraguayan guaraní', }, { name: 'Peru', capital: 'Lima', languages: ['Spanish'], population: 31488700, flag: 'https://restcountries.eu/data/per.svg', currency: 'Peruvian sol', }, { name: 'Philippines', capital: 'Manila', languages: ['English'], population: 103279800, flag: 'https://restcountries.eu/data/phl.svg', currency: 'Philippine peso', }, { name: 'Pitcairn', capital: 'Adamstown', languages: ['English'], population: 56, flag: 'https://restcountries.eu/data/pcn.svg', currency: 'New Zealand dollar', }, { name: 'Poland', capital: 'Warsaw', languages: ['Polish'], population: 38437239, flag: 'https://restcountries.eu/data/pol.svg', currency: 'Polish złoty', }, { name: 'Portugal', capital: 'Lisbon', languages: ['Portuguese'], population: 10374822, flag: 'https://restcountries.eu/data/prt.svg', currency: 'Euro', }, { name: 'Puerto Rico', capital: 'San Juan', languages: ['Spanish', 'English'], population: 3474182, flag: 'https://restcountries.eu/data/pri.svg', currency: 'United States dollar', }, { name: 'Qatar', capital: 'Doha', languages: ['Arabic'], population: 2587564, flag: 'https://restcountries.eu/data/qat.svg', currency: 'Qatari riyal', }, { name: 'Republic of Kosovo', capital: 'Pristina', languages: ['Albanian', 'Serbian'], population: 1733842, flag: 'https://restcountries.eu/data/kos.svg', currency: 'Euro', }, { name: 'Réunion', capital: 'Saint-Denis', languages: ['French'], population: 840974, flag: 'https://restcountries.eu/data/reu.svg', currency: 'Euro', }, { name: 'Romania', capital: 'Bucharest', languages: ['Romanian'], population: 19861408, flag: 'https://restcountries.eu/data/rou.svg', currency: 'Romanian leu', }, { name: 'Russian Federation', capital: 'Moscow', languages: ['Russian'], population: 146599183, flag: 'https://restcountries.eu/data/rus.svg', currency: 'Russian ruble', }, { name: 'Rwanda', capital: 'Kigali', languages: ['Kinyarwanda', 'English', 'French'], population: 11553188, flag: 'https://restcountries.eu/data/rwa.svg', currency: 'Rwandan franc', }, { name: 'Saint Barthélemy', capital: 'Gustavia', languages: ['French'], population: 9417, flag: 'https://restcountries.eu/data/blm.svg', currency: 'Euro', }, { name: 'Saint Helena, Ascension and Tristan da Cunha', capital: 'Jamestown', languages: ['English'], population: 4255, flag: 'https://restcountries.eu/data/shn.svg', currency: 'Saint Helena pound', }, { name: 'Saint Kitts and Nevis', capital: 'Basseterre', languages: ['English'], population: 46204, flag: 'https://restcountries.eu/data/kna.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Lucia', capital: 'Castries', languages: ['English'], population: 186000, flag: 'https://restcountries.eu/data/lca.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Martin (French part)', capital: 'Marigot', languages: ['English', 'French', 'Dutch'], population: 36979, flag: 'https://restcountries.eu/data/maf.svg', currency: 'Euro', }, { name: 'Saint Pierre and Miquelon', capital: 'Saint-Pierre', languages: ['French'], population: 6069, flag: 'https://restcountries.eu/data/spm.svg', currency: 'Euro', }, { name: 'Saint Vincent and the Grenadines', capital: 'Kingstown', languages: ['English'], population: 109991, flag: 'https://restcountries.eu/data/vct.svg', currency: 'East Caribbean dollar', }, { name: 'Samoa', capital: 'Apia', languages: ['Samoan', 'English'], population: 194899, flag: 'https://restcountries.eu/data/wsm.svg', currency: 'Samoan tālā', }, { name: 'San Marino', capital: 'City of San Marino', languages: ['Italian'], population: 33005, flag: 'https://restcountries.eu/data/smr.svg', currency: 'Euro', }, { name: 'Sao Tome and Principe', capital: 'São Tomé', languages: ['Portuguese'], population: 187356, flag: 'https://restcountries.eu/data/stp.svg', currency: 'São Tomé and Príncipe dobra', }, { name: 'Saudi Arabia', capital: 'Riyadh', languages: ['Arabic'], population: 32248200, flag: 'https://restcountries.eu/data/sau.svg', currency: 'Saudi riyal', }, { name: 'Senegal', capital: 'Dakar', languages: ['French'], population: 14799859, flag: 'https://restcountries.eu/data/sen.svg', currency: 'West African CFA franc', }, { name: 'Serbia', capital: 'Belgrade', languages: ['Serbian'], population: 7076372, flag: 'https://restcountries.eu/data/srb.svg', currency: 'Serbian dinar', }, { name: 'Seychelles', capital: 'Victoria', languages: ['French', 'English'], population: 91400, flag: 'https://restcountries.eu/data/syc.svg', currency: 'Seychellois rupee', }, { name: 'Sierra Leone', capital: 'Freetown', languages: ['English'], population: 7075641, flag: 'https://restcountries.eu/data/sle.svg', currency: 'Sierra Leonean leone', }, { name: 'Singapore', capital: 'Singapore', languages: ['English', 'Malay', 'Tamil', 'Chinese'], population: 5535000, flag: 'https://restcountries.eu/data/sgp.svg', currency: 'Brunei dollar', }, { name: 'Sint Maarten (Dutch part)', capital: 'Philipsburg', languages: ['Dutch', 'English'], population: 38247, flag: 'https://restcountries.eu/data/sxm.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Slovakia', capital: 'Bratislava', languages: ['Slovak'], population: 5426252, flag: 'https://restcountries.eu/data/svk.svg', currency: 'Euro', }, { name: 'Slovenia', capital: 'Ljubljana', languages: ['Slovene'], population: 2064188, flag: 'https://restcountries.eu/data/svn.svg', currency: 'Euro', }, { name: 'Solomon Islands', capital: 'Honiara', languages: ['English'], population: 642000, flag: 'https://restcountries.eu/data/slb.svg', currency: 'Solomon Islands dollar', }, { name: 'Somalia', capital: 'Mogadishu', languages: ['Somali', 'Arabic'], population: 11079000, flag: 'https://restcountries.eu/data/som.svg', currency: 'Somali shilling', }, { name: 'South Africa', capital: 'Pretoria', languages: [ 'Afrikaans', 'English', 'Southern Ndebele', 'Southern Sotho', 'Swati', 'Tswana', 'Tsonga', 'Venda', 'Xhosa', 'Zulu', ], population: 55653654, flag: 'https://restcountries.eu/data/zaf.svg', currency: 'South African rand', }, { name: 'South Georgia and the South Sandwich Islands', capital: 'King Edward Point', languages: ['English'], population: 30, flag: 'https://restcountries.eu/data/sgs.svg', currency: 'British pound', }, { name: 'Korea (Republic of)', capital: 'Seoul', languages: ['Korean'], population: 50801405, flag: 'https://restcountries.eu/data/kor.svg', currency: 'South Korean won', }, { name: 'South Sudan', capital: 'Juba', languages: ['English'], population: 12131000, flag: 'https://restcountries.eu/data/ssd.svg', currency: 'South Sudanese pound', }, { name: 'Spain', capital: 'Madrid', languages: ['Spanish'], population: 46438422, flag: 'https://restcountries.eu/data/esp.svg', currency: 'Euro', }, { name: 'Sri Lanka', capital: 'Colombo', languages: ['Sinhalese', 'Tamil'], population: 20966000, flag: 'https://restcountries.eu/data/lka.svg', currency: 'Sri Lankan rupee', }, { name: 'Sudan', capital: 'Khartoum', languages: ['Arabic', 'English'], population: 39598700, flag: 'https://restcountries.eu/data/sdn.svg', currency: 'Sudanese pound', }, { name: 'Suriname', capital: 'Paramaribo', languages: ['Dutch'], population: 541638, flag: 'https://restcountries.eu/data/sur.svg', currency: 'Surinamese dollar', }, { name: 'Svalbard and Jan Mayen', capital: 'Longyearbyen', languages: ['Norwegian'], population: 2562, flag: 'https://restcountries.eu/data/sjm.svg', currency: 'Norwegian krone', }, { name: 'Swaziland', capital: 'Lobamba', languages: ['English', 'Swati'], population: 1132657, flag: 'https://restcountries.eu/data/swz.svg', currency: 'Swazi lilangeni', }, { name: 'Sweden', capital: 'Stockholm', languages: ['Swedish'], population: 9894888, flag: 'https://restcountries.eu/data/swe.svg', currency: 'Swedish krona', }, { name: 'Switzerland', capital: 'Bern', languages: ['German', 'French', 'Italian'], population: 8341600, flag: 'https://restcountries.eu/data/che.svg', currency: 'Swiss franc', }, { name: 'Syrian Arab Republic', capital: 'Damascus', languages: ['Arabic'], population: 18564000, flag: 'https://restcountries.eu/data/syr.svg', currency: 'Syrian pound', }, { name: 'Taiwan', capital: 'Taipei', languages: ['Chinese'], population: 23503349, flag: 'https://restcountries.eu/data/twn.svg', currency: 'New Taiwan dollar', }, { name: 'Tajikistan', capital: 'Dushanbe', languages: ['Tajik', 'Russian'], population: 8593600, flag: 'https://restcountries.eu/data/tjk.svg', currency: 'Tajikistani somoni', }, { name: 'Tanzania, United Republic of', capital: 'Dodoma', languages: ['Swahili', 'English'], population: 55155000, flag: 'https://restcountries.eu/data/tza.svg', currency: 'Tanzanian shilling', }, { name: 'Thailand', capital: 'Bangkok', languages: ['Thai'], population: 65327652, flag: 'https://restcountries.eu/data/tha.svg', currency: 'Thai baht', }, { name: 'Timor-Leste', capital: 'Dili', languages: ['Portuguese'], population: 1167242, flag: 'https://restcountries.eu/data/tls.svg', currency: 'United States dollar', }, { name: 'Togo', capital: 'Lomé', languages: ['French'], population: 7143000, flag: 'https://restcountries.eu/data/tgo.svg', currency: 'West African CFA franc', }, { name: 'Tokelau', capital: 'Fakaofo', languages: ['English'], population: 1411, flag: 'https://restcountries.eu/data/tkl.svg', currency: 'New Zealand dollar', }, { name: 'Tonga', capital: "Nuku'alofa", languages: ['English', 'Tonga (Tonga Islands)'], population: 103252, flag: 'https://restcountries.eu/data/ton.svg', currency: 'Tongan paʻanga', }, { name: 'Trinidad and Tobago', capital: 'Port of Spain', languages: ['English'], population: 1349667, flag: 'https://restcountries.eu/data/tto.svg', currency: 'Trinidad and Tobago dollar', }, { name: 'Tunisia', capital: 'Tunis', languages: ['Arabic'], population: 11154400, flag: 'https://restcountries.eu/data/tun.svg', currency: 'Tunisian dinar', }, { name: 'Turkey', capital: 'Ankara', languages: ['Turkish'], population: 78741053, flag: 'https://restcountries.eu/data/tur.svg', currency: 'Turkish lira', }, { name: 'Turkmenistan', capital: 'Ashgabat', languages: ['Turkmen', 'Russian'], population: 4751120, flag: 'https://restcountries.eu/data/tkm.svg', currency: 'Turkmenistan manat', }, { name: 'Turks and Caicos Islands', capital: 'Cockburn Town', languages: ['English'], population: 31458, flag: 'https://restcountries.eu/data/tca.svg', currency: 'United States dollar', }, { name: 'Tuvalu', capital: 'Funafuti', languages: ['English'], population: 10640, flag: 'https://restcountries.eu/data/tuv.svg', currency: 'Australian dollar', }, { name: 'Uganda', capital: 'Kampala', languages: ['English', 'Swahili'], population: 33860700, flag: 'https://restcountries.eu/data/uga.svg', currency: 'Ugandan shilling', }, { name: 'Ukraine', capital: 'Kiev', languages: ['Ukrainian'], population: 42692393, flag: 'https://restcountries.eu/data/ukr.svg', currency: 'Ukrainian hryvnia', }, { name: 'United Arab Emirates', capital: 'Abu Dhabi', languages: ['Arabic'], population: 9856000, flag: 'https://restcountries.eu/data/are.svg', currency: 'United Arab Emirates dirham', }, { name: 'United Kingdom of Great Britain and Northern Ireland', capital: 'London', languages: ['English'], population: 65110000, flag: 'https://restcountries.eu/data/gbr.svg', currency: 'British pound', }, { name: 'United States of America', capital: 'Washington, D.C.', languages: ['English'], population: 323947000, flag: 'https://restcountries.eu/data/usa.svg', currency: 'United States dollar', }, { name: 'Uruguay', capital: 'Montevideo', languages: ['Spanish'], population: 3480222, flag: 'https://restcountries.eu/data/ury.svg', currency: 'Uruguayan peso', }, { name: 'Uzbekistan', capital: 'Tashkent', languages: ['Uzbek', 'Russian'], population: 31576400, flag: 'https://restcountries.eu/data/uzb.svg', currency: "Uzbekistani so'm", }, { name: 'Vanuatu', capital: 'Port Vila', languages: ['Bislama', 'English', 'French'], population: 277500, flag: 'https://restcountries.eu/data/vut.svg', currency: 'Vanuatu vatu', }, { name: 'Venezuela (Bolivarian Republic of)', capital: 'Caracas', languages: ['Spanish'], population: 31028700, flag: 'https://restcountries.eu/data/ven.svg', currency: 'Venezuelan bolívar', }, { name: 'Viet Nam', capital: 'Hanoi', languages: ['Vietnamese'], population: 92700000, flag: 'https://restcountries.eu/data/vnm.svg', currency: 'Vietnamese đồng', }, { name: 'Wallis and Futuna', capital: 'Mata-Utu', languages: ['French'], population: 11750, flag: 'https://restcountries.eu/data/wlf.svg', currency: 'CFP franc', }, { name: 'Western Sahara', capital: 'El Aaiún', languages: ['Spanish'], population: 510713, flag: 'https://restcountries.eu/data/esh.svg', currency: 'Moroccan dirham', }, { name: 'Yemen', capital: "Sana'a", languages: ['Arabic'], population: 27478000, flag: 'https://restcountries.eu/data/yem.svg', currency: 'Yemeni rial', }, { name: 'Zambia', capital: 'Lusaka', languages: ['English'], population: 15933883, flag: 'https://restcountries.eu/data/zmb.svg', currency: 'Zambian kwacha', }, { name: 'Zimbabwe', capital: 'Harare', languages: ['English', 'Shona', 'Northern Ndebele'], population: 14240168, flag: 'https://restcountries.eu/data/zwe.svg', currency: 'Botswana pula', }, ] ================================================ FILE: 07_Day_Class_Components/07_class_based_components_boilerplate/src/data/ten_most_highest_populations.js ================================================ export const tenHighestPopulation = [ { country: 'World', population: 7693165599 }, { country: 'China', population: 1377422166 }, { country: 'India', population: 1295210000 }, { country: 'United States of America', population: 323947000 }, { country: 'Indonesia', population: 258705000 }, { country: 'Brazil', population: 206135893 }, { country: 'Pakistan', population: 194125062 }, { country: 'Nigeria', population: 186988000 }, { country: 'Bangladesh', population: 161006790 }, { country: 'Russian Federation', population: 146599183 }, { country: 'Japan', population: 126960000 }, ] ================================================ FILE: 07_Day_Class_Components/07_class_based_components_boilerplate/src/index.js ================================================ // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' // Fuction to show month date year // User Card Component const UserCard = ({ user: { firstName, lastName, image } }) => (
    {firstName}

    {firstName} {lastName}

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 18, color: 'white', } // class based component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } // TechList Component // class base component class TechList extends React.Component { constructor(props) { super(props) } render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { constructor(props) { super(props) } render() { return (

    Prerequisite to get started react.js:

    ) } } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } handleTime = () => { alert(this.showDate(new Date())) } greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } render() { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 7, 2020', } const techs = ['HTML', 'CSS', 'JavaScript'] // copying the author from data object to user variable using spread operator const user = { ...data.author, image: asabenehImage } return (
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ================================================ FILE: 07_Day_Class_Components/07_class_components.md ================================================

    30 Days Of React: Class Components

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 6](../06_Day_Map_List_Keys/06_map_list_keys.md) | [Day 8 >>](../08_Day_States/08_states.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_7.jpg) - [Class Components](#class-components) - [Accessing props in Class components](#accessing-props-in-class-components) - [Methods in Class based component](#methods-in-class-based-component) - [Exercises](#exercises) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # Class Components In the previous sections, we have covered JSX, functional component and props. In this section, we will cover class components or stateful component. Only class based components used to have state and life cycle methods. However, after React version 16.8.0 functional components can have state and life cycle using React Hooks. In 30 Days Of React challenge, we will cover React before 16.8.0 and after, that mean both old and newest version. There are lots of codes written in older version and at some point it may need migration. In addition, to understand React very well someone has to understand class based component too. All the previous components are functional components. Let us make also class based component. Class based component is made using JavaScript class and it inherits from react Component. Let us learn how to make a class based component by converting all the functional components we made previously. It is not important to convert all but we are converting them for the sake of learning how to change functional components to class components. ```js // Pure JavaScript class and child // Imagine this what we import from React package class Component { constructor(props) {} } // This how we make class based components by inheriting from the parent class Child extends Component { constructor(props) { super(props) } } ``` Functional React component ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // Header Component // Functional component const Header = () => (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 6, 2020
    ) const rootElement = document.getElementById('root') ReactDOM.render(
    , rootElement) ``` Class based React component is a child of React.Component and it has a built-in render method and it may have a constructor. ```js //index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { render() { return (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 7, 2020
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(
    , rootElement) ``` Let's see the above component with a constructor ```js //index.js import React from 'react' import ReactDOM from 'react-dom' // class base component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { return (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 7, 2020
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(
    , rootElement) ``` Let's change all the functional component to class based components ```js // TechList Component // functional component const TechList = () => { const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } // TechList Component // class base component class TechList extends React.Component { constructor(props) { super(props) } render() { const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Functional Component const Main = () => (

    Prerequisite to get started react.js:

    ) // Main Component // Class Component class Main extends React.Component { constructor(props) { super(props) } render() { return (

    Prerequisite to get started react.js:

    ) } } // Footer Component // Functional component const Footer = () => (

    Copyright 2020

    ) // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright 2020

    ) } } // The App, or the parent or the container component // Functional Component const App = () => (
    ) // The App, or the parent or the container component // Class Component class App extends React.Component { constructor(props) { super(props) } render() { return (
    ) } } ``` Let's put all the class based components together in one file. ```js //index.js import React from 'react' import ReactDOM from 'react-dom' // class base component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { return (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 7, 2020
    ) } } // TechList Component // class base component class TechList extends React.Component { constructor(props) { super(props) } render() { const techs = ['HTML', 'CSS', 'JavaScript'] const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { constructor(props) { super(props) } render() { return (

    Prerequisite to get started react.js:

    ) } } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright 2020

    ) } } // The App, or the parent or the container component // Class Component class App extends React.Component { constructor(props) { super(props) } render() { return (
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Accessing props in Class components We stated that props is a means to send data from on component to another or we can call it that props is a data carrier. Therefore, we should handle props in class based component too. We can access props of a class based component using the keyword _this_. See the example below. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { return (

    {this.props.data.welcome}

    {this.props.data.title}

    {this.props.data.author.firstName} {this.props.data.author.lastName}

    {this.props.data.date}
    ) } } const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 7, 2020', } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` As you can see in the above example, to get the data out from props we have write _props.data_ every time. We can avoid this repetition using destructuring. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const App = () => { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 6, 2020', } return (
    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` As you can see, the above code cleaner than the previous. Now, let's clean all the components we have and put all together. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } // TechList Component // class base component class TechList extends React.Component { constructor(props) { super(props) } render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { constructor(props) { super(props) } render() { return (

    Prerequisite to get started react.js:

    ) } } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { render() { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 7, 2020', } const techs = ['HTML', 'CSS', 'JavaScript'] return (
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Methods in Class based component We access methods in class based component. Most of the time, we write different methods on the parent component and we pass them to child components. Let's see the implementation. Let's add a method on this component. ```js //index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } render() { return (

    Welcome to 30 Days Of React

    Getting Started React

    JavaScript Library

    Asabeneh Yetayeh

    Oct 7, 2020
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(
    , rootElement) ``` The invoking or calling of the method triggers when the event occurs. Therefore, whenever you pass a method to an event listener do not invoke the method. Now, let's the code we had add all the necessary methods. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' // Fuction to show month date year // User Card Component const UserCard = ({ user: { firstName, lastName, image } }) => (
    {firstName}

    {firstName} {lastName}

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 18, color: 'white', } // class based component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } // TechList Component // class base component class TechList extends React.Component { constructor(props) { super(props) } render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { constructor(props) { super(props) } render() { return (

    Prerequisite to get started react.js:

    ) } } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } handleTime = () => { alert(this.showDate(new Date())) } greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } render() { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 7, 2020', } const techs = ['HTML', 'CSS', 'JavaScript'] // copying the author from data object to user variable using spread operator const user = { ...data.author, image: asabenehImage } return (
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Most of the time the container or the parent component can be written as class component and others as functional or presentational components. Data usually flows from parent components to child component and it is unidirectional. However, the latest version of react can allow us to write every component in our application only with functional components. This was impossible in previous versions. In next section, we will cover state which is the heart of React. State allows React component to rerender when whenever there is a change in state. # Exercises ## Exercises: Level 1 1. How do you write a pure JavaScript function 2. What is inheritance and how do you make a child from a parent class? 3. What is class based React component ? 4. What is the difference between functional React component and class based React component ? 5. When do we need to use class based components instead of functional components 6. What is the use cases of class based component ? 7. Which type of component do use most frequently ? functional or class-based component 8. What is React life cycle ? (not covered yet) ? 9. What is state in React ? (not covered yet) ## Exercises: Level 2 Learn more about class based component by changing previous days exercises to class based components ## Exercises: Level 3 Coming ... 🎉 CONGRATULATIONS ! 🎉 [<< Day 6](../06_Day_Map_List_Keys/06_map_list_keys.md) | [Day 8 >>](../08_Day_States/08_states.md) ================================================ FILE: 08_Day_States/08_states.md ================================================

    30 Days Of React: States

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 7](../07_Day_Class_Components/07_class_components.md) | [Day 9 >>](../09_Day_Conditional_Rendering/09_conditional_rendering.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_8.jpg) - [States](#states) - [What is State?](#what-is-state) - [How to set a state](#how-to-set-a-state) - [Resetting a state using a JavaScript method](#resetting-a-state-using-a-javascript-method) - [Exercises](#exercises) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # States ## What is State? What is state ? The English meaning of state is _the particular condition that someone or something is in at a specific time_. Let us see some states being something - Are you happy or sad? - Is light on or off ? Is present or absent ? - Is full or empty ? For instance, I am happy because I am enjoying creating 30 Days Of React challenge. I believe that you are happy too. State is an object in react which let the component re-render when state data changes. ## How to set a state We set an initial state inside the constructor or outside the constructor of a class based component. We do not directly change or mutate the state but we use the _setState()_ method to reset to a new state. . As you can see below in the state object we have count with initial value 0. We can access the state object using _this.state_ and the property name. See the example below. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { // declaring state state = { count: 0, } render() { // accessing the state value const count = this.state.count return (

    {count}

    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` If you run the above code you will see zero on the browser. We can increase or decrease the value the state by changing the value of the state using JavaScript method. ## Resetting a state using a JavaScript method Now, let's add some methods which increase or decrease the value of count by clicking a button. Let us add a button to increase and a button to decrease the value of count. To set the state we use react method _this.setState_. See the example below ```js // index.js import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { // declaring state state = { count: 0, } render() { // accessing the state value const count = this.state.count return (

    {count}

    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` If you understand the above example, adding minus one method will be easy. Let us add the minus one method on the click event. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { // declaring state state = { count: 0, } render() { // accessing the state value const count = this.state.count return (

    {count}

    {' '}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Both button work well, but we need to re-structure the code well. Let us create separate methods in the component. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { // declaring state state = { count: 0, } // method which add one to the state addOne = () => { this.setState({ count: this.state.count + 1 }) } // method which subtract one to the state minusOne = () => { this.setState({ count: this.state.count - 1 }) } render() { // accessing the state value const count = this.state.count return (

    {count}

    {' '}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Let us do more example about state, in the following example we will develop small application which shows either a dog or cat. We can start by setting the initial state with cat then when it is clicked it will show dog and alternatively. We need one method which changes the animal alternatively. See the code below. If you want to see live click [here](https://codepen.io/Asabeneh/full/LYVxKpq). ```js // index.js import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { // declaring state state = { image: 'https://www.smithsstationah.com/imagebank/eVetSites/Feline/01.jpg', } changeAnimal = () => { let dogURL = 'https://static.onecms.io/wp-content/uploads/sites/12/2015/04/dogs-pembroke-welsh-corgi-400x400.jpg' let catURL = 'https://www.smithsstationah.com/imagebank/eVetSites/Feline/01.jpg' let image = this.state.image === catURL ? dogURL : catURL this.setState({ image }) } render() { // accessing the state value const count = this.state.count return (

    30 Days Of React

    animal
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Now, let's put all the codes we have so far and also let's implement state when it is necessary. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' // Fuction to show month date year const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // User Card Component const UserCard = ({ user: { firstName, lastName, image } }) => (
    {firstName}

    {firstName} {lastName}

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 18, color: 'white', } // class based component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const Count = ({ count, addOne, minusOne }) => (

    {count}

    ) // TechList Component // class base component class TechList extends React.Component { constructor(props) { super(props) } render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { constructor(props) { super(props) } render() { const { techs, user, greetPeople, handleTime, changeBackground, count, addOne, minusOne, } = this.props return (

    Prerequisite to get started react.js:

    ) } } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { state = { count: 0, styles: { backgroundColor: '', color: '', }, } showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } addOne = () => { this.setState({ count: this.state.count + 1 }) } // method which subtract one to the state minusOne = () => { this.setState({ count: this.state.count - 1 }) } handleTime = () => { alert(this.showDate(new Date())) } greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } changeBackground = () => {} render() { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 7, 2020', } const techs = ['HTML', 'CSS', 'JavaScript'] const date = new Date() // copying the author from data object to user variable using spread operator const user = { ...data.author, image: asabenehImage } return (
    {this.state.backgroundColor}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` I believe that now you have a very good understanding of state. After this, we will use state in other sections too because state and props is the core of a react application. ## Exercises ### Exercises: Level 1 1. What was your state today? Are you happy? I hope so. If you manage to make it this far you should be happy. 2. What is state in React ? 3. What is the difference between props and state in React ? 4. How do you access state in a React component ? 5. How do you set a set in a React component ? ### Exercises: Level 2 1. Use React state to change the background of the page. You can use this technique to apply a dark mode for your portfolio. ![Change Background](../images/08_day_changing_background_exercise.gif) 2. After long time of lock down, you may think of travelling and you do not know where to go. You may be interested to develop a random country selector that selects your holiday destination. ![Change Background](../images/08_day_select_country_exercise.gif) ### Exercises: Level 3 Coming 🎉 CONGRATULATIONS ! 🎉 [<< Day 7](../07_Day_Class_Components/07_class_components.md) | [Day 9 >>](../09_Day_Conditional_Rendering/09_conditional_rendering.md) ================================================ FILE: 08_Day_States/08_states_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 08_Day_States/08_states_boilerplate/README.md ================================================ # 30 Days of React App: Day 8 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 08_Day_States/08_states_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 08_Day_States/08_states_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 08_Day_States/08_states_boilerplate/src/data/countries.js ================================================ export const countriesData = [ { name: 'Afghanistan', capital: 'Kabul', languages: ['Pashto', 'Uzbek', 'Turkmen'], population: 27657145, flag: 'https://restcountries.eu/data/afg.svg', currency: 'Afghan afghani', }, { name: 'Åland Islands', capital: 'Mariehamn', languages: ['Swedish'], population: 28875, flag: 'https://restcountries.eu/data/ala.svg', currency: 'Euro', }, { name: 'Albania', capital: 'Tirana', languages: ['Albanian'], population: 2886026, flag: 'https://restcountries.eu/data/alb.svg', currency: 'Albanian lek', }, { name: 'Algeria', capital: 'Algiers', languages: ['Arabic'], population: 40400000, flag: 'https://restcountries.eu/data/dza.svg', currency: 'Algerian dinar', }, { name: 'American Samoa', capital: 'Pago Pago', languages: ['English', 'Samoan'], population: 57100, flag: 'https://restcountries.eu/data/asm.svg', currency: 'United State Dollar', }, { name: 'Andorra', capital: 'Andorra la Vella', languages: ['Catalan'], population: 78014, flag: 'https://restcountries.eu/data/and.svg', currency: 'Euro', }, { name: 'Angola', capital: 'Luanda', languages: ['Portuguese'], population: 25868000, flag: 'https://restcountries.eu/data/ago.svg', currency: 'Angolan kwanza', }, { name: 'Anguilla', capital: 'The Valley', languages: ['English'], population: 13452, flag: 'https://restcountries.eu/data/aia.svg', currency: 'East Caribbean dollar', }, { name: 'Antarctica', capital: '', languages: ['English', 'Russian'], population: 1000, flag: 'https://restcountries.eu/data/ata.svg', currency: 'Australian dollar', }, { name: 'Antigua and Barbuda', capital: "Saint John's", languages: ['English'], population: 86295, flag: 'https://restcountries.eu/data/atg.svg', currency: 'East Caribbean dollar', }, { name: 'Argentina', capital: 'Buenos Aires', languages: ['Spanish', 'Guaraní'], population: 43590400, flag: 'https://restcountries.eu/data/arg.svg', currency: 'Argentine peso', }, { name: 'Armenia', capital: 'Yerevan', languages: ['Armenian', 'Russian'], population: 2994400, flag: 'https://restcountries.eu/data/arm.svg', currency: 'Armenian dram', }, { name: 'Aruba', capital: 'Oranjestad', languages: ['Dutch', '(Eastern) Punjabi'], population: 107394, flag: 'https://restcountries.eu/data/abw.svg', currency: 'Aruban florin', }, { name: 'Australia', capital: 'Canberra', languages: ['English'], population: 24117360, flag: 'https://restcountries.eu/data/aus.svg', currency: 'Australian dollar', }, { name: 'Austria', capital: 'Vienna', languages: ['German'], population: 8725931, flag: 'https://restcountries.eu/data/aut.svg', currency: 'Euro', }, { name: 'Azerbaijan', capital: 'Baku', languages: ['Azerbaijani'], population: 9730500, flag: 'https://restcountries.eu/data/aze.svg', currency: 'Azerbaijani manat', }, { name: 'Bahamas', capital: 'Nassau', languages: ['English'], population: 378040, flag: 'https://restcountries.eu/data/bhs.svg', currency: 'Bahamian dollar', }, { name: 'Bahrain', capital: 'Manama', languages: ['Arabic'], population: 1404900, flag: 'https://restcountries.eu/data/bhr.svg', currency: 'Bahraini dinar', }, { name: 'Bangladesh', capital: 'Dhaka', languages: ['Bengali'], population: 161006790, flag: 'https://restcountries.eu/data/bgd.svg', currency: 'Bangladeshi taka', }, { name: 'Barbados', capital: 'Bridgetown', languages: ['English'], population: 285000, flag: 'https://restcountries.eu/data/brb.svg', currency: 'Barbadian dollar', }, { name: 'Belarus', capital: 'Minsk', languages: ['Belarusian', 'Russian'], population: 9498700, flag: 'https://restcountries.eu/data/blr.svg', currency: 'New Belarusian ruble', }, { name: 'Belgium', capital: 'Brussels', languages: ['Dutch', 'French', 'German'], population: 11319511, flag: 'https://restcountries.eu/data/bel.svg', currency: 'Euro', }, { name: 'Belize', capital: 'Belmopan', languages: ['English', 'Spanish'], population: 370300, flag: 'https://restcountries.eu/data/blz.svg', currency: 'Belize dollar', }, { name: 'Benin', capital: 'Porto-Novo', languages: ['French'], population: 10653654, flag: 'https://restcountries.eu/data/ben.svg', currency: 'West African CFA franc', }, { name: 'Bermuda', capital: 'Hamilton', languages: ['English'], population: 61954, flag: 'https://restcountries.eu/data/bmu.svg', currency: 'Bermudian dollar', }, { name: 'Bhutan', capital: 'Thimphu', languages: ['Dzongkha'], population: 775620, flag: 'https://restcountries.eu/data/btn.svg', currency: 'Bhutanese ngultrum', }, { name: 'Bolivia (Plurinational State of)', capital: 'Sucre', languages: ['Spanish', 'Aymara', 'Quechua'], population: 10985059, flag: 'https://restcountries.eu/data/bol.svg', currency: 'Bolivian boliviano', }, { name: 'Bonaire, Sint Eustatius and Saba', capital: 'Kralendijk', languages: ['Dutch'], population: 17408, flag: 'https://restcountries.eu/data/bes.svg', currency: 'United States dollar', }, { name: 'Bosnia and Herzegovina', capital: 'Sarajevo', languages: ['Bosnian', 'Croatian', 'Serbian'], population: 3531159, flag: 'https://restcountries.eu/data/bih.svg', currency: 'Bosnia and Herzegovina convertible mark', }, { name: 'Botswana', capital: 'Gaborone', languages: ['English', 'Tswana'], population: 2141206, flag: 'https://restcountries.eu/data/bwa.svg', currency: 'Botswana pula', }, { name: 'Bouvet Island', capital: '', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 0, flag: 'https://restcountries.eu/data/bvt.svg', currency: 'Norwegian krone', }, { name: 'Brazil', capital: 'Brasília', languages: ['Portuguese'], population: 206135893, flag: 'https://restcountries.eu/data/bra.svg', currency: 'Brazilian real', }, { name: 'British Indian Ocean Territory', capital: 'Diego Garcia', languages: ['English'], population: 3000, flag: 'https://restcountries.eu/data/iot.svg', currency: 'United States dollar', }, { name: 'United States Minor Outlying Islands', capital: '', languages: ['English'], population: 300, flag: 'https://restcountries.eu/data/umi.svg', currency: 'United States Dollar', }, { name: 'Virgin Islands (British)', capital: 'Road Town', languages: ['English'], population: 28514, flag: 'https://restcountries.eu/data/vgb.svg', currency: '[D]', }, { name: 'Virgin Islands (U.S.)', capital: 'Charlotte Amalie', languages: ['English'], population: 114743, flag: 'https://restcountries.eu/data/vir.svg', currency: 'United States dollar', }, { name: 'Brunei Darussalam', capital: 'Bandar Seri Begawan', languages: ['Malay'], population: 411900, flag: 'https://restcountries.eu/data/brn.svg', currency: 'Brunei dollar', }, { name: 'Bulgaria', capital: 'Sofia', languages: ['Bulgarian'], population: 7153784, flag: 'https://restcountries.eu/data/bgr.svg', currency: 'Bulgarian lev', }, { name: 'Burkina Faso', capital: 'Ouagadougou', languages: ['French', 'Fula'], population: 19034397, flag: 'https://restcountries.eu/data/bfa.svg', currency: 'West African CFA franc', }, { name: 'Burundi', capital: 'Bujumbura', languages: ['French', 'Kirundi'], population: 10114505, flag: 'https://restcountries.eu/data/bdi.svg', currency: 'Burundian franc', }, { name: 'Cambodia', capital: 'Phnom Penh', languages: ['Khmer'], population: 15626444, flag: 'https://restcountries.eu/data/khm.svg', currency: 'Cambodian riel', }, { name: 'Cameroon', capital: 'Yaoundé', languages: ['English', 'French'], population: 22709892, flag: 'https://restcountries.eu/data/cmr.svg', currency: 'Central African CFA franc', }, { name: 'Canada', capital: 'Ottawa', languages: ['English', 'French'], population: 36155487, flag: 'https://restcountries.eu/data/can.svg', currency: 'Canadian dollar', }, { name: 'Cabo Verde', capital: 'Praia', languages: ['Portuguese'], population: 531239, flag: 'https://restcountries.eu/data/cpv.svg', currency: 'Cape Verdean escudo', }, { name: 'Cayman Islands', capital: 'George Town', languages: ['English'], population: 58238, flag: 'https://restcountries.eu/data/cym.svg', currency: 'Cayman Islands dollar', }, { name: 'Central African Republic', capital: 'Bangui', languages: ['French', 'Sango'], population: 4998000, flag: 'https://restcountries.eu/data/caf.svg', currency: 'Central African CFA franc', }, { name: 'Chad', capital: "N'Djamena", languages: ['French', 'Arabic'], population: 14497000, flag: 'https://restcountries.eu/data/tcd.svg', currency: 'Central African CFA franc', }, { name: 'Chile', capital: 'Santiago', languages: ['Spanish'], population: 18191900, flag: 'https://restcountries.eu/data/chl.svg', currency: 'Chilean peso', }, { name: 'China', capital: 'Beijing', languages: ['Chinese'], population: 1377422166, flag: 'https://restcountries.eu/data/chn.svg', currency: 'Chinese yuan', }, { name: 'Christmas Island', capital: 'Flying Fish Cove', languages: ['English'], population: 2072, flag: 'https://restcountries.eu/data/cxr.svg', currency: 'Australian dollar', }, { name: 'Cocos (Keeling) Islands', capital: 'West Island', languages: ['English'], population: 550, flag: 'https://restcountries.eu/data/cck.svg', currency: 'Australian dollar', }, { name: 'Colombia', capital: 'Bogotá', languages: ['Spanish'], population: 48759958, flag: 'https://restcountries.eu/data/col.svg', currency: 'Colombian peso', }, { name: 'Comoros', capital: 'Moroni', languages: ['Arabic', 'French'], population: 806153, flag: 'https://restcountries.eu/data/com.svg', currency: 'Comorian franc', }, { name: 'Congo', capital: 'Brazzaville', languages: ['French', 'Lingala'], population: 4741000, flag: 'https://restcountries.eu/data/cog.svg', currency: 'Central African CFA franc', }, { name: 'Congo (Democratic Republic of the)', capital: 'Kinshasa', languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], population: 85026000, flag: 'https://restcountries.eu/data/cod.svg', currency: 'Congolese franc', }, { name: 'Cook Islands', capital: 'Avarua', languages: ['English'], population: 18100, flag: 'https://restcountries.eu/data/cok.svg', currency: 'New Zealand dollar', }, { name: 'Costa Rica', capital: 'San José', languages: ['Spanish'], population: 4890379, flag: 'https://restcountries.eu/data/cri.svg', currency: 'Costa Rican colón', }, { name: 'Croatia', capital: 'Zagreb', languages: ['Croatian'], population: 4190669, flag: 'https://restcountries.eu/data/hrv.svg', currency: 'Croatian kuna', }, { name: 'Cuba', capital: 'Havana', languages: ['Spanish'], population: 11239004, flag: 'https://restcountries.eu/data/cub.svg', currency: 'Cuban convertible peso', }, { name: 'Curaçao', capital: 'Willemstad', languages: ['Dutch', '(Eastern) Punjabi', 'English'], population: 154843, flag: 'https://restcountries.eu/data/cuw.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Cyprus', capital: 'Nicosia', languages: ['Greek (modern)', 'Turkish', 'Armenian'], population: 847000, flag: 'https://restcountries.eu/data/cyp.svg', currency: 'Euro', }, { name: 'Czech Republic', capital: 'Prague', languages: ['Czech', 'Slovak'], population: 10558524, flag: 'https://restcountries.eu/data/cze.svg', currency: 'Czech koruna', }, { name: 'Denmark', capital: 'Copenhagen', languages: ['Danish'], population: 5717014, flag: 'https://restcountries.eu/data/dnk.svg', currency: 'Danish krone', }, { name: 'Djibouti', capital: 'Djibouti', languages: ['French', 'Arabic'], population: 900000, flag: 'https://restcountries.eu/data/dji.svg', currency: 'Djiboutian franc', }, { name: 'Dominica', capital: 'Roseau', languages: ['English'], population: 71293, flag: 'https://restcountries.eu/data/dma.svg', currency: 'East Caribbean dollar', }, { name: 'Dominican Republic', capital: 'Santo Domingo', languages: ['Spanish'], population: 10075045, flag: 'https://restcountries.eu/data/dom.svg', currency: 'Dominican peso', }, { name: 'Ecuador', capital: 'Quito', languages: ['Spanish'], population: 16545799, flag: 'https://restcountries.eu/data/ecu.svg', currency: 'United States dollar', }, { name: 'Egypt', capital: 'Cairo', languages: ['Arabic'], population: 91290000, flag: 'https://restcountries.eu/data/egy.svg', currency: 'Egyptian pound', }, { name: 'El Salvador', capital: 'San Salvador', languages: ['Spanish'], population: 6520675, flag: 'https://restcountries.eu/data/slv.svg', currency: 'United States dollar', }, { name: 'Equatorial Guinea', capital: 'Malabo', languages: ['Spanish', 'French'], population: 1222442, flag: 'https://restcountries.eu/data/gnq.svg', currency: 'Central African CFA franc', }, { name: 'Eritrea', capital: 'Asmara', languages: ['Tigrinya', 'Arabic', 'English'], population: 5352000, flag: 'https://restcountries.eu/data/eri.svg', currency: 'Eritrean nakfa', }, { name: 'Estonia', capital: 'Tallinn', languages: ['Estonian'], population: 1315944, flag: 'https://restcountries.eu/data/est.svg', currency: 'Euro', }, { name: 'Ethiopia', capital: 'Addis Ababa', languages: ['Amharic'], population: 92206005, flag: 'https://restcountries.eu/data/eth.svg', currency: 'Ethiopian birr', }, { name: 'Falkland Islands (Malvinas)', capital: 'Stanley', languages: ['English'], population: 2563, flag: 'https://restcountries.eu/data/flk.svg', currency: 'Falkland Islands pound', }, { name: 'Faroe Islands', capital: 'Tórshavn', languages: ['Faroese'], population: 49376, flag: 'https://restcountries.eu/data/fro.svg', currency: 'Danish krone', }, { name: 'Fiji', capital: 'Suva', languages: ['English', 'Fijian', 'Hindi', 'Urdu'], population: 867000, flag: 'https://restcountries.eu/data/fji.svg', currency: 'Fijian dollar', }, { name: 'Finland', capital: 'Helsinki', languages: ['Finnish', 'Swedish'], population: 5491817, flag: 'https://restcountries.eu/data/fin.svg', currency: 'Euro', }, { name: 'France', capital: 'Paris', languages: ['French'], population: 66710000, flag: 'https://restcountries.eu/data/fra.svg', currency: 'Euro', }, { name: 'French Guiana', capital: 'Cayenne', languages: ['French'], population: 254541, flag: 'https://restcountries.eu/data/guf.svg', currency: 'Euro', }, { name: 'French Polynesia', capital: 'Papeetē', languages: ['French'], population: 271800, flag: 'https://restcountries.eu/data/pyf.svg', currency: 'CFP franc', }, { name: 'French Southern Territories', capital: 'Port-aux-Français', languages: ['French'], population: 140, flag: 'https://restcountries.eu/data/atf.svg', currency: 'Euro', }, { name: 'Gabon', capital: 'Libreville', languages: ['French'], population: 1802278, flag: 'https://restcountries.eu/data/gab.svg', currency: 'Central African CFA franc', }, { name: 'Gambia', capital: 'Banjul', languages: ['English'], population: 1882450, flag: 'https://restcountries.eu/data/gmb.svg', currency: 'Gambian dalasi', }, { name: 'Georgia', capital: 'Tbilisi', languages: ['Georgian'], population: 3720400, flag: 'https://restcountries.eu/data/geo.svg', currency: 'Georgian Lari', }, { name: 'Germany', capital: 'Berlin', languages: ['German'], population: 81770900, flag: 'https://restcountries.eu/data/deu.svg', currency: 'Euro', }, { name: 'Ghana', capital: 'Accra', languages: ['English'], population: 27670174, flag: 'https://restcountries.eu/data/gha.svg', currency: 'Ghanaian cedi', }, { name: 'Gibraltar', capital: 'Gibraltar', languages: ['English'], population: 33140, flag: 'https://restcountries.eu/data/gib.svg', currency: 'Gibraltar pound', }, { name: 'Greece', capital: 'Athens', languages: ['Greek (modern)'], population: 10858018, flag: 'https://restcountries.eu/data/grc.svg', currency: 'Euro', }, { name: 'Greenland', capital: 'Nuuk', languages: ['Kalaallisut'], population: 55847, flag: 'https://restcountries.eu/data/grl.svg', currency: 'Danish krone', }, { name: 'Grenada', capital: "St. George's", languages: ['English'], population: 103328, flag: 'https://restcountries.eu/data/grd.svg', currency: 'East Caribbean dollar', }, { name: 'Guadeloupe', capital: 'Basse-Terre', languages: ['French'], population: 400132, flag: 'https://restcountries.eu/data/glp.svg', currency: 'Euro', }, { name: 'Guam', capital: 'Hagåtña', languages: ['English', 'Chamorro', 'Spanish'], population: 184200, flag: 'https://restcountries.eu/data/gum.svg', currency: 'United States dollar', }, { name: 'Guatemala', capital: 'Guatemala City', languages: ['Spanish'], population: 16176133, flag: 'https://restcountries.eu/data/gtm.svg', currency: 'Guatemalan quetzal', }, { name: 'Guernsey', capital: 'St. Peter Port', languages: ['English', 'French'], population: 62999, flag: 'https://restcountries.eu/data/ggy.svg', currency: 'British pound', }, { name: 'Guinea', capital: 'Conakry', languages: ['French', 'Fula'], population: 12947000, flag: 'https://restcountries.eu/data/gin.svg', currency: 'Guinean franc', }, { name: 'Guinea-Bissau', capital: 'Bissau', languages: ['Portuguese'], population: 1547777, flag: 'https://restcountries.eu/data/gnb.svg', currency: 'West African CFA franc', }, { name: 'Guyana', capital: 'Georgetown', languages: ['English'], population: 746900, flag: 'https://restcountries.eu/data/guy.svg', currency: 'Guyanese dollar', }, { name: 'Haiti', capital: 'Port-au-Prince', languages: ['French', 'Haitian'], population: 11078033, flag: 'https://restcountries.eu/data/hti.svg', currency: 'Haitian gourde', }, { name: 'Heard Island and McDonald Islands', capital: '', languages: ['English'], population: 0, flag: 'https://restcountries.eu/data/hmd.svg', currency: 'Australian dollar', }, { name: 'Holy See', capital: 'Rome', languages: ['Latin', 'Italian', 'French', 'German'], population: 451, flag: 'https://restcountries.eu/data/vat.svg', currency: 'Euro', }, { name: 'Honduras', capital: 'Tegucigalpa', languages: ['Spanish'], population: 8576532, flag: 'https://restcountries.eu/data/hnd.svg', currency: 'Honduran lempira', }, { name: 'Hong Kong', capital: 'City of Victoria', languages: ['English', 'Chinese'], population: 7324300, flag: 'https://restcountries.eu/data/hkg.svg', currency: 'Hong Kong dollar', }, { name: 'Hungary', capital: 'Budapest', languages: ['Hungarian'], population: 9823000, flag: 'https://restcountries.eu/data/hun.svg', currency: 'Hungarian forint', }, { name: 'Iceland', capital: 'Reykjavík', languages: ['Icelandic'], population: 334300, flag: 'https://restcountries.eu/data/isl.svg', currency: 'Icelandic króna', }, { name: 'India', capital: 'New Delhi', languages: ['Hindi', 'English'], population: 1295210000, flag: 'https://restcountries.eu/data/ind.svg', currency: 'Indian rupee', }, { name: 'Indonesia', capital: 'Jakarta', languages: ['Indonesian'], population: 258705000, flag: 'https://restcountries.eu/data/idn.svg', currency: 'Indonesian rupiah', }, { name: "Côte d'Ivoire", capital: 'Yamoussoukro', languages: ['French'], population: 22671331, flag: 'https://restcountries.eu/data/civ.svg', currency: 'West African CFA franc', }, { name: 'Iran (Islamic Republic of)', capital: 'Tehran', languages: ['Persian (Farsi)'], population: 79369900, flag: 'https://restcountries.eu/data/irn.svg', currency: 'Iranian rial', }, { name: 'Iraq', capital: 'Baghdad', languages: ['Arabic', 'Kurdish'], population: 37883543, flag: 'https://restcountries.eu/data/irq.svg', currency: 'Iraqi dinar', }, { name: 'Ireland', capital: 'Dublin', languages: ['Irish', 'English'], population: 6378000, flag: 'https://restcountries.eu/data/irl.svg', currency: 'Euro', }, { name: 'Isle of Man', capital: 'Douglas', languages: ['English', 'Manx'], population: 84497, flag: 'https://restcountries.eu/data/imn.svg', currency: 'British pound', }, { name: 'Israel', capital: 'Jerusalem', languages: ['Hebrew (modern)', 'Arabic'], population: 8527400, flag: 'https://restcountries.eu/data/isr.svg', currency: 'Israeli new shekel', }, { name: 'Italy', capital: 'Rome', languages: ['Italian'], population: 60665551, flag: 'https://restcountries.eu/data/ita.svg', currency: 'Euro', }, { name: 'Jamaica', capital: 'Kingston', languages: ['English'], population: 2723246, flag: 'https://restcountries.eu/data/jam.svg', currency: 'Jamaican dollar', }, { name: 'Japan', capital: 'Tokyo', languages: ['Japanese'], population: 126960000, flag: 'https://restcountries.eu/data/jpn.svg', currency: 'Japanese yen', }, { name: 'Jersey', capital: 'Saint Helier', languages: ['English', 'French'], population: 100800, flag: 'https://restcountries.eu/data/jey.svg', currency: 'British pound', }, { name: 'Jordan', capital: 'Amman', languages: ['Arabic'], population: 9531712, flag: 'https://restcountries.eu/data/jor.svg', currency: 'Jordanian dinar', }, { name: 'Kazakhstan', capital: 'Astana', languages: ['Kazakh', 'Russian'], population: 17753200, flag: 'https://restcountries.eu/data/kaz.svg', currency: 'Kazakhstani tenge', }, { name: 'Kenya', capital: 'Nairobi', languages: ['English', 'Swahili'], population: 47251000, flag: 'https://restcountries.eu/data/ken.svg', currency: 'Kenyan shilling', }, { name: 'Kiribati', capital: 'South Tarawa', languages: ['English'], population: 113400, flag: 'https://restcountries.eu/data/kir.svg', currency: 'Australian dollar', }, { name: 'Kuwait', capital: 'Kuwait City', languages: ['Arabic'], population: 4183658, flag: 'https://restcountries.eu/data/kwt.svg', currency: 'Kuwaiti dinar', }, { name: 'Kyrgyzstan', capital: 'Bishkek', languages: ['Kyrgyz', 'Russian'], population: 6047800, flag: 'https://restcountries.eu/data/kgz.svg', currency: 'Kyrgyzstani som', }, { name: "Lao People's Democratic Republic", capital: 'Vientiane', languages: ['Lao'], population: 6492400, flag: 'https://restcountries.eu/data/lao.svg', currency: 'Lao kip', }, { name: 'Latvia', capital: 'Riga', languages: ['Latvian'], population: 1961600, flag: 'https://restcountries.eu/data/lva.svg', currency: 'Euro', }, { name: 'Lebanon', capital: 'Beirut', languages: ['Arabic', 'French'], population: 5988000, flag: 'https://restcountries.eu/data/lbn.svg', currency: 'Lebanese pound', }, { name: 'Lesotho', capital: 'Maseru', languages: ['English', 'Southern Sotho'], population: 1894194, flag: 'https://restcountries.eu/data/lso.svg', currency: 'Lesotho loti', }, { name: 'Liberia', capital: 'Monrovia', languages: ['English'], population: 4615000, flag: 'https://restcountries.eu/data/lbr.svg', currency: 'Liberian dollar', }, { name: 'Libya', capital: 'Tripoli', languages: ['Arabic'], population: 6385000, flag: 'https://restcountries.eu/data/lby.svg', currency: 'Libyan dinar', }, { name: 'Liechtenstein', capital: 'Vaduz', languages: ['German'], population: 37623, flag: 'https://restcountries.eu/data/lie.svg', currency: 'Swiss franc', }, { name: 'Lithuania', capital: 'Vilnius', languages: ['Lithuanian'], population: 2872294, flag: 'https://restcountries.eu/data/ltu.svg', currency: 'Euro', }, { name: 'Luxembourg', capital: 'Luxembourg', languages: ['French', 'German', 'Luxembourgish'], population: 576200, flag: 'https://restcountries.eu/data/lux.svg', currency: 'Euro', }, { name: 'Macao', capital: '', languages: ['Chinese', 'Portuguese'], population: 649100, flag: 'https://restcountries.eu/data/mac.svg', currency: 'Macanese pataca', }, { name: 'Macedonia (the former Yugoslav Republic of)', capital: 'Skopje', languages: ['Macedonian'], population: 2058539, flag: 'https://restcountries.eu/data/mkd.svg', currency: 'Macedonian denar', }, { name: 'Madagascar', capital: 'Antananarivo', languages: ['French', 'Malagasy'], population: 22434363, flag: 'https://restcountries.eu/data/mdg.svg', currency: 'Malagasy ariary', }, { name: 'Malawi', capital: 'Lilongwe', languages: ['English', 'Chichewa'], population: 16832910, flag: 'https://restcountries.eu/data/mwi.svg', currency: 'Malawian kwacha', }, { name: 'Malaysia', capital: 'Kuala Lumpur', languages: ['Malaysian'], population: 31405416, flag: 'https://restcountries.eu/data/mys.svg', currency: 'Malaysian ringgit', }, { name: 'Maldives', capital: 'Malé', languages: ['Divehi'], population: 344023, flag: 'https://restcountries.eu/data/mdv.svg', currency: 'Maldivian rufiyaa', }, { name: 'Mali', capital: 'Bamako', languages: ['French'], population: 18135000, flag: 'https://restcountries.eu/data/mli.svg', currency: 'West African CFA franc', }, { name: 'Malta', capital: 'Valletta', languages: ['Maltese', 'English'], population: 425384, flag: 'https://restcountries.eu/data/mlt.svg', currency: 'Euro', }, { name: 'Marshall Islands', capital: 'Majuro', languages: ['English', 'Marshallese'], population: 54880, flag: 'https://restcountries.eu/data/mhl.svg', currency: 'United States dollar', }, { name: 'Martinique', capital: 'Fort-de-France', languages: ['French'], population: 378243, flag: 'https://restcountries.eu/data/mtq.svg', currency: 'Euro', }, { name: 'Mauritania', capital: 'Nouakchott', languages: ['Arabic'], population: 3718678, flag: 'https://restcountries.eu/data/mrt.svg', currency: 'Mauritanian ouguiya', }, { name: 'Mauritius', capital: 'Port Louis', languages: ['English'], population: 1262879, flag: 'https://restcountries.eu/data/mus.svg', currency: 'Mauritian rupee', }, { name: 'Mayotte', capital: 'Mamoudzou', languages: ['French'], population: 226915, flag: 'https://restcountries.eu/data/myt.svg', currency: 'Euro', }, { name: 'Mexico', capital: 'Mexico City', languages: ['Spanish'], population: 122273473, flag: 'https://restcountries.eu/data/mex.svg', currency: 'Mexican peso', }, { name: 'Micronesia (Federated States of)', capital: 'Palikir', languages: ['English'], population: 102800, flag: 'https://restcountries.eu/data/fsm.svg', currency: '[D]', }, { name: 'Moldova (Republic of)', capital: 'Chișinău', languages: ['Romanian'], population: 3553100, flag: 'https://restcountries.eu/data/mda.svg', currency: 'Moldovan leu', }, { name: 'Monaco', capital: 'Monaco', languages: ['French'], population: 38400, flag: 'https://restcountries.eu/data/mco.svg', currency: 'Euro', }, { name: 'Mongolia', capital: 'Ulan Bator', languages: ['Mongolian'], population: 3093100, flag: 'https://restcountries.eu/data/mng.svg', currency: 'Mongolian tögrög', }, { name: 'Montenegro', capital: 'Podgorica', languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], population: 621810, flag: 'https://restcountries.eu/data/mne.svg', currency: 'Euro', }, { name: 'Montserrat', capital: 'Plymouth', languages: ['English'], population: 4922, flag: 'https://restcountries.eu/data/msr.svg', currency: 'East Caribbean dollar', }, { name: 'Morocco', capital: 'Rabat', languages: ['Arabic'], population: 33337529, flag: 'https://restcountries.eu/data/mar.svg', currency: 'Moroccan dirham', }, { name: 'Mozambique', capital: 'Maputo', languages: ['Portuguese'], population: 26423700, flag: 'https://restcountries.eu/data/moz.svg', currency: 'Mozambican metical', }, { name: 'Myanmar', capital: 'Naypyidaw', languages: ['Burmese'], population: 51419420, flag: 'https://restcountries.eu/data/mmr.svg', currency: 'Burmese kyat', }, { name: 'Namibia', capital: 'Windhoek', languages: ['English', 'Afrikaans'], population: 2324388, flag: 'https://restcountries.eu/data/nam.svg', currency: 'Namibian dollar', }, { name: 'Nauru', capital: 'Yaren', languages: ['English', 'Nauruan'], population: 10084, flag: 'https://restcountries.eu/data/nru.svg', currency: 'Australian dollar', }, { name: 'Nepal', capital: 'Kathmandu', languages: ['Nepali'], population: 28431500, flag: 'https://restcountries.eu/data/npl.svg', currency: 'Nepalese rupee', }, { name: 'Netherlands', capital: 'Amsterdam', languages: ['Dutch'], population: 17019800, flag: 'https://restcountries.eu/data/nld.svg', currency: 'Euro', }, { name: 'New Caledonia', capital: 'Nouméa', languages: ['French'], population: 268767, flag: 'https://restcountries.eu/data/ncl.svg', currency: 'CFP franc', }, { name: 'New Zealand', capital: 'Wellington', languages: ['English', 'Māori'], population: 4697854, flag: 'https://restcountries.eu/data/nzl.svg', currency: 'New Zealand dollar', }, { name: 'Nicaragua', capital: 'Managua', languages: ['Spanish'], population: 6262703, flag: 'https://restcountries.eu/data/nic.svg', currency: 'Nicaraguan córdoba', }, { name: 'Niger', capital: 'Niamey', languages: ['French'], population: 20715000, flag: 'https://restcountries.eu/data/ner.svg', currency: 'West African CFA franc', }, { name: 'Nigeria', capital: 'Abuja', languages: ['English'], population: 186988000, flag: 'https://restcountries.eu/data/nga.svg', currency: 'Nigerian naira', }, { name: 'Niue', capital: 'Alofi', languages: ['English'], population: 1470, flag: 'https://restcountries.eu/data/niu.svg', currency: 'New Zealand dollar', }, { name: 'Norfolk Island', capital: 'Kingston', languages: ['English'], population: 2302, flag: 'https://restcountries.eu/data/nfk.svg', currency: 'Australian dollar', }, { name: "Korea (Democratic People's Republic of)", capital: 'Pyongyang', languages: ['Korean'], population: 25281000, flag: 'https://restcountries.eu/data/prk.svg', currency: 'North Korean won', }, { name: 'Northern Mariana Islands', capital: 'Saipan', languages: ['English', 'Chamorro'], population: 56940, flag: 'https://restcountries.eu/data/mnp.svg', currency: 'United States dollar', }, { name: 'Norway', capital: 'Oslo', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 5223256, flag: 'https://restcountries.eu/data/nor.svg', currency: 'Norwegian krone', }, { name: 'Oman', capital: 'Muscat', languages: ['Arabic'], population: 4420133, flag: 'https://restcountries.eu/data/omn.svg', currency: 'Omani rial', }, { name: 'Pakistan', capital: 'Islamabad', languages: ['English', 'Urdu'], population: 194125062, flag: 'https://restcountries.eu/data/pak.svg', currency: 'Pakistani rupee', }, { name: 'Palau', capital: 'Ngerulmud', languages: ['English'], population: 17950, flag: 'https://restcountries.eu/data/plw.svg', currency: '[E]', }, { name: 'Palestine, State of', capital: 'Ramallah', languages: ['Arabic'], population: 4682467, flag: 'https://restcountries.eu/data/pse.svg', currency: 'Israeli new sheqel', }, { name: 'Panama', capital: 'Panama City', languages: ['Spanish'], population: 3814672, flag: 'https://restcountries.eu/data/pan.svg', currency: 'Panamanian balboa', }, { name: 'Papua New Guinea', capital: 'Port Moresby', languages: ['English'], population: 8083700, flag: 'https://restcountries.eu/data/png.svg', currency: 'Papua New Guinean kina', }, { name: 'Paraguay', capital: 'Asunción', languages: ['Spanish', 'Guaraní'], population: 6854536, flag: 'https://restcountries.eu/data/pry.svg', currency: 'Paraguayan guaraní', }, { name: 'Peru', capital: 'Lima', languages: ['Spanish'], population: 31488700, flag: 'https://restcountries.eu/data/per.svg', currency: 'Peruvian sol', }, { name: 'Philippines', capital: 'Manila', languages: ['English'], population: 103279800, flag: 'https://restcountries.eu/data/phl.svg', currency: 'Philippine peso', }, { name: 'Pitcairn', capital: 'Adamstown', languages: ['English'], population: 56, flag: 'https://restcountries.eu/data/pcn.svg', currency: 'New Zealand dollar', }, { name: 'Poland', capital: 'Warsaw', languages: ['Polish'], population: 38437239, flag: 'https://restcountries.eu/data/pol.svg', currency: 'Polish złoty', }, { name: 'Portugal', capital: 'Lisbon', languages: ['Portuguese'], population: 10374822, flag: 'https://restcountries.eu/data/prt.svg', currency: 'Euro', }, { name: 'Puerto Rico', capital: 'San Juan', languages: ['Spanish', 'English'], population: 3474182, flag: 'https://restcountries.eu/data/pri.svg', currency: 'United States dollar', }, { name: 'Qatar', capital: 'Doha', languages: ['Arabic'], population: 2587564, flag: 'https://restcountries.eu/data/qat.svg', currency: 'Qatari riyal', }, { name: 'Republic of Kosovo', capital: 'Pristina', languages: ['Albanian', 'Serbian'], population: 1733842, flag: 'https://restcountries.eu/data/kos.svg', currency: 'Euro', }, { name: 'Réunion', capital: 'Saint-Denis', languages: ['French'], population: 840974, flag: 'https://restcountries.eu/data/reu.svg', currency: 'Euro', }, { name: 'Romania', capital: 'Bucharest', languages: ['Romanian'], population: 19861408, flag: 'https://restcountries.eu/data/rou.svg', currency: 'Romanian leu', }, { name: 'Russian Federation', capital: 'Moscow', languages: ['Russian'], population: 146599183, flag: 'https://restcountries.eu/data/rus.svg', currency: 'Russian ruble', }, { name: 'Rwanda', capital: 'Kigali', languages: ['Kinyarwanda', 'English', 'French'], population: 11553188, flag: 'https://restcountries.eu/data/rwa.svg', currency: 'Rwandan franc', }, { name: 'Saint Barthélemy', capital: 'Gustavia', languages: ['French'], population: 9417, flag: 'https://restcountries.eu/data/blm.svg', currency: 'Euro', }, { name: 'Saint Helena, Ascension and Tristan da Cunha', capital: 'Jamestown', languages: ['English'], population: 4255, flag: 'https://restcountries.eu/data/shn.svg', currency: 'Saint Helena pound', }, { name: 'Saint Kitts and Nevis', capital: 'Basseterre', languages: ['English'], population: 46204, flag: 'https://restcountries.eu/data/kna.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Lucia', capital: 'Castries', languages: ['English'], population: 186000, flag: 'https://restcountries.eu/data/lca.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Martin (French part)', capital: 'Marigot', languages: ['English', 'French', 'Dutch'], population: 36979, flag: 'https://restcountries.eu/data/maf.svg', currency: 'Euro', }, { name: 'Saint Pierre and Miquelon', capital: 'Saint-Pierre', languages: ['French'], population: 6069, flag: 'https://restcountries.eu/data/spm.svg', currency: 'Euro', }, { name: 'Saint Vincent and the Grenadines', capital: 'Kingstown', languages: ['English'], population: 109991, flag: 'https://restcountries.eu/data/vct.svg', currency: 'East Caribbean dollar', }, { name: 'Samoa', capital: 'Apia', languages: ['Samoan', 'English'], population: 194899, flag: 'https://restcountries.eu/data/wsm.svg', currency: 'Samoan tālā', }, { name: 'San Marino', capital: 'City of San Marino', languages: ['Italian'], population: 33005, flag: 'https://restcountries.eu/data/smr.svg', currency: 'Euro', }, { name: 'Sao Tome and Principe', capital: 'São Tomé', languages: ['Portuguese'], population: 187356, flag: 'https://restcountries.eu/data/stp.svg', currency: 'São Tomé and Príncipe dobra', }, { name: 'Saudi Arabia', capital: 'Riyadh', languages: ['Arabic'], population: 32248200, flag: 'https://restcountries.eu/data/sau.svg', currency: 'Saudi riyal', }, { name: 'Senegal', capital: 'Dakar', languages: ['French'], population: 14799859, flag: 'https://restcountries.eu/data/sen.svg', currency: 'West African CFA franc', }, { name: 'Serbia', capital: 'Belgrade', languages: ['Serbian'], population: 7076372, flag: 'https://restcountries.eu/data/srb.svg', currency: 'Serbian dinar', }, { name: 'Seychelles', capital: 'Victoria', languages: ['French', 'English'], population: 91400, flag: 'https://restcountries.eu/data/syc.svg', currency: 'Seychellois rupee', }, { name: 'Sierra Leone', capital: 'Freetown', languages: ['English'], population: 7075641, flag: 'https://restcountries.eu/data/sle.svg', currency: 'Sierra Leonean leone', }, { name: 'Singapore', capital: 'Singapore', languages: ['English', 'Malay', 'Tamil', 'Chinese'], population: 5535000, flag: 'https://restcountries.eu/data/sgp.svg', currency: 'Brunei dollar', }, { name: 'Sint Maarten (Dutch part)', capital: 'Philipsburg', languages: ['Dutch', 'English'], population: 38247, flag: 'https://restcountries.eu/data/sxm.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Slovakia', capital: 'Bratislava', languages: ['Slovak'], population: 5426252, flag: 'https://restcountries.eu/data/svk.svg', currency: 'Euro', }, { name: 'Slovenia', capital: 'Ljubljana', languages: ['Slovene'], population: 2064188, flag: 'https://restcountries.eu/data/svn.svg', currency: 'Euro', }, { name: 'Solomon Islands', capital: 'Honiara', languages: ['English'], population: 642000, flag: 'https://restcountries.eu/data/slb.svg', currency: 'Solomon Islands dollar', }, { name: 'Somalia', capital: 'Mogadishu', languages: ['Somali', 'Arabic'], population: 11079000, flag: 'https://restcountries.eu/data/som.svg', currency: 'Somali shilling', }, { name: 'South Africa', capital: 'Pretoria', languages: [ 'Afrikaans', 'English', 'Southern Ndebele', 'Southern Sotho', 'Swati', 'Tswana', 'Tsonga', 'Venda', 'Xhosa', 'Zulu', ], population: 55653654, flag: 'https://restcountries.eu/data/zaf.svg', currency: 'South African rand', }, { name: 'South Georgia and the South Sandwich Islands', capital: 'King Edward Point', languages: ['English'], population: 30, flag: 'https://restcountries.eu/data/sgs.svg', currency: 'British pound', }, { name: 'Korea (Republic of)', capital: 'Seoul', languages: ['Korean'], population: 50801405, flag: 'https://restcountries.eu/data/kor.svg', currency: 'South Korean won', }, { name: 'South Sudan', capital: 'Juba', languages: ['English'], population: 12131000, flag: 'https://restcountries.eu/data/ssd.svg', currency: 'South Sudanese pound', }, { name: 'Spain', capital: 'Madrid', languages: ['Spanish'], population: 46438422, flag: 'https://restcountries.eu/data/esp.svg', currency: 'Euro', }, { name: 'Sri Lanka', capital: 'Colombo', languages: ['Sinhalese', 'Tamil'], population: 20966000, flag: 'https://restcountries.eu/data/lka.svg', currency: 'Sri Lankan rupee', }, { name: 'Sudan', capital: 'Khartoum', languages: ['Arabic', 'English'], population: 39598700, flag: 'https://restcountries.eu/data/sdn.svg', currency: 'Sudanese pound', }, { name: 'Suriname', capital: 'Paramaribo', languages: ['Dutch'], population: 541638, flag: 'https://restcountries.eu/data/sur.svg', currency: 'Surinamese dollar', }, { name: 'Svalbard and Jan Mayen', capital: 'Longyearbyen', languages: ['Norwegian'], population: 2562, flag: 'https://restcountries.eu/data/sjm.svg', currency: 'Norwegian krone', }, { name: 'Swaziland', capital: 'Lobamba', languages: ['English', 'Swati'], population: 1132657, flag: 'https://restcountries.eu/data/swz.svg', currency: 'Swazi lilangeni', }, { name: 'Sweden', capital: 'Stockholm', languages: ['Swedish'], population: 9894888, flag: 'https://restcountries.eu/data/swe.svg', currency: 'Swedish krona', }, { name: 'Switzerland', capital: 'Bern', languages: ['German', 'French', 'Italian'], population: 8341600, flag: 'https://restcountries.eu/data/che.svg', currency: 'Swiss franc', }, { name: 'Syrian Arab Republic', capital: 'Damascus', languages: ['Arabic'], population: 18564000, flag: 'https://restcountries.eu/data/syr.svg', currency: 'Syrian pound', }, { name: 'Taiwan', capital: 'Taipei', languages: ['Chinese'], population: 23503349, flag: 'https://restcountries.eu/data/twn.svg', currency: 'New Taiwan dollar', }, { name: 'Tajikistan', capital: 'Dushanbe', languages: ['Tajik', 'Russian'], population: 8593600, flag: 'https://restcountries.eu/data/tjk.svg', currency: 'Tajikistani somoni', }, { name: 'Tanzania, United Republic of', capital: 'Dodoma', languages: ['Swahili', 'English'], population: 55155000, flag: 'https://restcountries.eu/data/tza.svg', currency: 'Tanzanian shilling', }, { name: 'Thailand', capital: 'Bangkok', languages: ['Thai'], population: 65327652, flag: 'https://restcountries.eu/data/tha.svg', currency: 'Thai baht', }, { name: 'Timor-Leste', capital: 'Dili', languages: ['Portuguese'], population: 1167242, flag: 'https://restcountries.eu/data/tls.svg', currency: 'United States dollar', }, { name: 'Togo', capital: 'Lomé', languages: ['French'], population: 7143000, flag: 'https://restcountries.eu/data/tgo.svg', currency: 'West African CFA franc', }, { name: 'Tokelau', capital: 'Fakaofo', languages: ['English'], population: 1411, flag: 'https://restcountries.eu/data/tkl.svg', currency: 'New Zealand dollar', }, { name: 'Tonga', capital: "Nuku'alofa", languages: ['English', 'Tonga (Tonga Islands)'], population: 103252, flag: 'https://restcountries.eu/data/ton.svg', currency: 'Tongan paʻanga', }, { name: 'Trinidad and Tobago', capital: 'Port of Spain', languages: ['English'], population: 1349667, flag: 'https://restcountries.eu/data/tto.svg', currency: 'Trinidad and Tobago dollar', }, { name: 'Tunisia', capital: 'Tunis', languages: ['Arabic'], population: 11154400, flag: 'https://restcountries.eu/data/tun.svg', currency: 'Tunisian dinar', }, { name: 'Turkey', capital: 'Ankara', languages: ['Turkish'], population: 78741053, flag: 'https://restcountries.eu/data/tur.svg', currency: 'Turkish lira', }, { name: 'Turkmenistan', capital: 'Ashgabat', languages: ['Turkmen', 'Russian'], population: 4751120, flag: 'https://restcountries.eu/data/tkm.svg', currency: 'Turkmenistan manat', }, { name: 'Turks and Caicos Islands', capital: 'Cockburn Town', languages: ['English'], population: 31458, flag: 'https://restcountries.eu/data/tca.svg', currency: 'United States dollar', }, { name: 'Tuvalu', capital: 'Funafuti', languages: ['English'], population: 10640, flag: 'https://restcountries.eu/data/tuv.svg', currency: 'Australian dollar', }, { name: 'Uganda', capital: 'Kampala', languages: ['English', 'Swahili'], population: 33860700, flag: 'https://restcountries.eu/data/uga.svg', currency: 'Ugandan shilling', }, { name: 'Ukraine', capital: 'Kiev', languages: ['Ukrainian'], population: 42692393, flag: 'https://restcountries.eu/data/ukr.svg', currency: 'Ukrainian hryvnia', }, { name: 'United Arab Emirates', capital: 'Abu Dhabi', languages: ['Arabic'], population: 9856000, flag: 'https://restcountries.eu/data/are.svg', currency: 'United Arab Emirates dirham', }, { name: 'United Kingdom of Great Britain and Northern Ireland', capital: 'London', languages: ['English'], population: 65110000, flag: 'https://restcountries.eu/data/gbr.svg', currency: 'British pound', }, { name: 'United States of America', capital: 'Washington, D.C.', languages: ['English'], population: 323947000, flag: 'https://restcountries.eu/data/usa.svg', currency: 'United States dollar', }, { name: 'Uruguay', capital: 'Montevideo', languages: ['Spanish'], population: 3480222, flag: 'https://restcountries.eu/data/ury.svg', currency: 'Uruguayan peso', }, { name: 'Uzbekistan', capital: 'Tashkent', languages: ['Uzbek', 'Russian'], population: 31576400, flag: 'https://restcountries.eu/data/uzb.svg', currency: "Uzbekistani so'm", }, { name: 'Vanuatu', capital: 'Port Vila', languages: ['Bislama', 'English', 'French'], population: 277500, flag: 'https://restcountries.eu/data/vut.svg', currency: 'Vanuatu vatu', }, { name: 'Venezuela (Bolivarian Republic of)', capital: 'Caracas', languages: ['Spanish'], population: 31028700, flag: 'https://restcountries.eu/data/ven.svg', currency: 'Venezuelan bolívar', }, { name: 'Viet Nam', capital: 'Hanoi', languages: ['Vietnamese'], population: 92700000, flag: 'https://restcountries.eu/data/vnm.svg', currency: 'Vietnamese đồng', }, { name: 'Wallis and Futuna', capital: 'Mata-Utu', languages: ['French'], population: 11750, flag: 'https://restcountries.eu/data/wlf.svg', currency: 'CFP franc', }, { name: 'Western Sahara', capital: 'El Aaiún', languages: ['Spanish'], population: 510713, flag: 'https://restcountries.eu/data/esh.svg', currency: 'Moroccan dirham', }, { name: 'Yemen', capital: "Sana'a", languages: ['Arabic'], population: 27478000, flag: 'https://restcountries.eu/data/yem.svg', currency: 'Yemeni rial', }, { name: 'Zambia', capital: 'Lusaka', languages: ['English'], population: 15933883, flag: 'https://restcountries.eu/data/zmb.svg', currency: 'Zambian kwacha', }, { name: 'Zimbabwe', capital: 'Harare', languages: ['English', 'Shona', 'Northern Ndebele'], population: 14240168, flag: 'https://restcountries.eu/data/zwe.svg', currency: 'Botswana pula', }, ] ================================================ FILE: 08_Day_States/08_states_boilerplate/src/data/ten_most_highest_populations.js ================================================ export const tenHighestPopulation = [ { country: 'World', population: 7693165599 }, { country: 'China', population: 1377422166 }, { country: 'India', population: 1295210000 }, { country: 'United States of America', population: 323947000 }, { country: 'Indonesia', population: 258705000 }, { country: 'Brazil', population: 206135893 }, { country: 'Pakistan', population: 194125062 }, { country: 'Nigeria', population: 186988000 }, { country: 'Bangladesh', population: 161006790 }, { country: 'Russian Federation', population: 146599183 }, { country: 'Japan', population: 126960000 }, ] ================================================ FILE: 08_Day_States/08_states_boilerplate/src/index.js ================================================ // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images/asabeneh.jpg' // Fuction to show month date year const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } // User Card Component const UserCard = ({ user: { firstName, lastName, image } }) => (
    {firstName}

    {firstName} {lastName}

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 18, color: 'white', } // class based component class Header extends React.Component { constructor(props) { super(props) // the code inside the constructor run before any other code } render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const Count = ({ count, addOne, minusOne }) => (

    {count}

    ) // TechList Component // class base component class TechList extends React.Component { constructor(props) { super(props) } render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { constructor(props) { super(props) } render() { const { techs, user, greetPeople, handleTime, changeBackground, count, addOne, minusOne, } = this.props return (

    Prerequisite to get started react.js:

    ) } } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { state = { count: 0, styles: { backgroundColor: '', color: '', }, } showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return ` ${month} ${date}, ${year}` } addOne = () => { this.setState({ count: this.state.count + 1 }) } // method which subtract one to the state minusOne = () => { this.setState({ count: this.state.count - 1 }) } handleTime = () => { alert(this.showDate(new Date())) } greetPeople = () => { alert('Welcome to 30 Days Of React Challenge, 2020') } changeBackground = () => {} render() { const data = { welcome: 'Welcome to 30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 7, 2020', } const techs = ['HTML', 'CSS', 'JavaScript'] const date = new Date() // copying the author from data object to user variable using spread operator const user = { ...data.author, image: asabenehImage } return (
    {this.state.backgroundColor}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering.md ================================================

    30 Days Of React: Conditional Rendering

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_React_Project_Folder_Structure/10_react_project_folder_structure.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_9.jpg) # Conditional Rendering As we can understand from the term, conditional rendering is a way to render different JSX or component at different condition. We can implement conditional rendering using regular if and else statement, ternary operator and &&. Let's implement a different conditional rendering. ## Conditional Rendering using If and Else statement In the code below, we have an initial state of loggedIn which is false. If the state is false we inform user to log in otherwise we welcome the user. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { render() { const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}

    Select a country for your next holiday

    ) } } class App extends React.Component { state = { loggedIn: false, } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } // conditional rendering using if and else statement let status if (this.state.loggedIn) { status =

    Welcome to 30 Days Of React

    } else { status =

    Please Login

    } return (
    {status}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Let's add a method which allow as to toggle the status of the user. We should have a button to handle event for logging in and logging out. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } class App extends React.Component { state = { loggedIn: false, } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } let status let text if (this.state.loggedIn) { status =

    Welcome to 30 Days Of React

    text = 'Logout' } else { status =

    Please Login

    text = 'Login' } return (
    {status}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` How about if our condition is more than two? Like pure JavaScript we can use if else if statement. In general, conditional rendering is not different from pure JavaScript conditional statement. ## Conditional Rendering using Ternary Operator Ternary operator is an an alternative for if else statement. However, there is more use cases for ternary operator than if else statement. For example, use can use ternary operator inside styles, className or many places in a component than regular if else statement. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } class App extends React.Component { state = { loggedIn: false, } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } let status = this.state.loggedIn ? (

    Welcome to 30 Days Of React

    ) : (

    Please Login

    ) return (
    {status}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` In addition to JSX, we can also conditionally render a component. Let's change the above conditional JSX to a component. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const Login = () => (

    Please Login

    ) const Welcome = (props) => (

    Welcome to 30 Days Of React

    ) class App extends React.Component { state = { loggedIn: false, } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } const status = this.state.loggedIn ? : return (
    {status}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Conditional Rendering using && Operator The && operator render the right JSX operand if the left operand(expression) is true. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const Login = () => (

    Please Login

    ) const Welcome = (props) => (

    Welcome to 30 Days Of React

    ) class App extends React.Component { state = { loggedIn: false, techs: ['HTML', 'CSS', 'JS'], } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } // We can destructure state const { loggedIn, techs } = this.state const status = loggedIn ? : return (
    {status}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` In the previous section, we used alert box to greet people and also to display time. Let's render the greeting and time on browser DOM instead of displaying on alert box. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const Message = ({ message }) => (

    {message}

    ) const Login = () => (

    Please Login

    ) const Welcome = (props) => (

    Welcome to 30 Days Of React

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // TechList Component // class base component class TechList extends React.Component { render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { render() { const { techs, greetPeople, handleTime, loggedIn, handleLogin, message, } = this.props console.log(message) const status = loggedIn ? : return (

    Prerequisite to get started react.js:

    {techs.length === 3 && (

    You have all the prerequisite courses to get started React

    )}
    ) } } // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { state = { loggedIn: false, techs: ['HTML', 'CSS', 'JS'], message: 'Click show time or Greet people to change me', } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return `${month} ${date}, ${year}` } handleTime = () => { let message = this.showDate(new Date()) this.setState({ message }) } greetPeople = () => { let message = 'Welcome to 30 Days Of React Challenge, 2020' this.setState({ message }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } return (
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Testimony Now it is time to express your thoughts about the Author and 30DaysOfReact. You can leave your testimonial on this [link](https://www.asabeneh.com/testimonials) ## Exercises ### Exercises: Level 1 1. What is conditional rendering? 2. How do you implement conditional rendering? 3. Which method of conditional rendering do you prefer to use? ### Exercises: Level 2 1. Make a single page application which changes the body of the background based on the season of the year(Autumn, Winter, Spring, Summer) 2. Make a single page application which change the body of the background based on the time of the day(Morning, Noon, Evening, Night) ### Exercises: Level 3 1. Fetching data takes some amount of time. A user has to wait until the data get loaded. Implement a loading functionality of a data is not fetched yet. You can simulate the delay using setTimeout. 🎉 CONGRATULATIONS ! 🎉 [<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_React_Project_Folder_Structure/10_react_project_folder_structure.md) ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering_boilerplate/README.md ================================================ # 30 Days of React App: Day 9 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering_boilerplate/src/data/countries.js ================================================ export const countriesData = [ { name: 'Afghanistan', capital: 'Kabul', languages: ['Pashto', 'Uzbek', 'Turkmen'], population: 27657145, flag: 'https://restcountries.eu/data/afg.svg', currency: 'Afghan afghani', }, { name: 'Åland Islands', capital: 'Mariehamn', languages: ['Swedish'], population: 28875, flag: 'https://restcountries.eu/data/ala.svg', currency: 'Euro', }, { name: 'Albania', capital: 'Tirana', languages: ['Albanian'], population: 2886026, flag: 'https://restcountries.eu/data/alb.svg', currency: 'Albanian lek', }, { name: 'Algeria', capital: 'Algiers', languages: ['Arabic'], population: 40400000, flag: 'https://restcountries.eu/data/dza.svg', currency: 'Algerian dinar', }, { name: 'American Samoa', capital: 'Pago Pago', languages: ['English', 'Samoan'], population: 57100, flag: 'https://restcountries.eu/data/asm.svg', currency: 'United State Dollar', }, { name: 'Andorra', capital: 'Andorra la Vella', languages: ['Catalan'], population: 78014, flag: 'https://restcountries.eu/data/and.svg', currency: 'Euro', }, { name: 'Angola', capital: 'Luanda', languages: ['Portuguese'], population: 25868000, flag: 'https://restcountries.eu/data/ago.svg', currency: 'Angolan kwanza', }, { name: 'Anguilla', capital: 'The Valley', languages: ['English'], population: 13452, flag: 'https://restcountries.eu/data/aia.svg', currency: 'East Caribbean dollar', }, { name: 'Antarctica', capital: '', languages: ['English', 'Russian'], population: 1000, flag: 'https://restcountries.eu/data/ata.svg', currency: 'Australian dollar', }, { name: 'Antigua and Barbuda', capital: "Saint John's", languages: ['English'], population: 86295, flag: 'https://restcountries.eu/data/atg.svg', currency: 'East Caribbean dollar', }, { name: 'Argentina', capital: 'Buenos Aires', languages: ['Spanish', 'Guaraní'], population: 43590400, flag: 'https://restcountries.eu/data/arg.svg', currency: 'Argentine peso', }, { name: 'Armenia', capital: 'Yerevan', languages: ['Armenian', 'Russian'], population: 2994400, flag: 'https://restcountries.eu/data/arm.svg', currency: 'Armenian dram', }, { name: 'Aruba', capital: 'Oranjestad', languages: ['Dutch', '(Eastern) Punjabi'], population: 107394, flag: 'https://restcountries.eu/data/abw.svg', currency: 'Aruban florin', }, { name: 'Australia', capital: 'Canberra', languages: ['English'], population: 24117360, flag: 'https://restcountries.eu/data/aus.svg', currency: 'Australian dollar', }, { name: 'Austria', capital: 'Vienna', languages: ['German'], population: 8725931, flag: 'https://restcountries.eu/data/aut.svg', currency: 'Euro', }, { name: 'Azerbaijan', capital: 'Baku', languages: ['Azerbaijani'], population: 9730500, flag: 'https://restcountries.eu/data/aze.svg', currency: 'Azerbaijani manat', }, { name: 'Bahamas', capital: 'Nassau', languages: ['English'], population: 378040, flag: 'https://restcountries.eu/data/bhs.svg', currency: 'Bahamian dollar', }, { name: 'Bahrain', capital: 'Manama', languages: ['Arabic'], population: 1404900, flag: 'https://restcountries.eu/data/bhr.svg', currency: 'Bahraini dinar', }, { name: 'Bangladesh', capital: 'Dhaka', languages: ['Bengali'], population: 161006790, flag: 'https://restcountries.eu/data/bgd.svg', currency: 'Bangladeshi taka', }, { name: 'Barbados', capital: 'Bridgetown', languages: ['English'], population: 285000, flag: 'https://restcountries.eu/data/brb.svg', currency: 'Barbadian dollar', }, { name: 'Belarus', capital: 'Minsk', languages: ['Belarusian', 'Russian'], population: 9498700, flag: 'https://restcountries.eu/data/blr.svg', currency: 'New Belarusian ruble', }, { name: 'Belgium', capital: 'Brussels', languages: ['Dutch', 'French', 'German'], population: 11319511, flag: 'https://restcountries.eu/data/bel.svg', currency: 'Euro', }, { name: 'Belize', capital: 'Belmopan', languages: ['English', 'Spanish'], population: 370300, flag: 'https://restcountries.eu/data/blz.svg', currency: 'Belize dollar', }, { name: 'Benin', capital: 'Porto-Novo', languages: ['French'], population: 10653654, flag: 'https://restcountries.eu/data/ben.svg', currency: 'West African CFA franc', }, { name: 'Bermuda', capital: 'Hamilton', languages: ['English'], population: 61954, flag: 'https://restcountries.eu/data/bmu.svg', currency: 'Bermudian dollar', }, { name: 'Bhutan', capital: 'Thimphu', languages: ['Dzongkha'], population: 775620, flag: 'https://restcountries.eu/data/btn.svg', currency: 'Bhutanese ngultrum', }, { name: 'Bolivia (Plurinational State of)', capital: 'Sucre', languages: ['Spanish', 'Aymara', 'Quechua'], population: 10985059, flag: 'https://restcountries.eu/data/bol.svg', currency: 'Bolivian boliviano', }, { name: 'Bonaire, Sint Eustatius and Saba', capital: 'Kralendijk', languages: ['Dutch'], population: 17408, flag: 'https://restcountries.eu/data/bes.svg', currency: 'United States dollar', }, { name: 'Bosnia and Herzegovina', capital: 'Sarajevo', languages: ['Bosnian', 'Croatian', 'Serbian'], population: 3531159, flag: 'https://restcountries.eu/data/bih.svg', currency: 'Bosnia and Herzegovina convertible mark', }, { name: 'Botswana', capital: 'Gaborone', languages: ['English', 'Tswana'], population: 2141206, flag: 'https://restcountries.eu/data/bwa.svg', currency: 'Botswana pula', }, { name: 'Bouvet Island', capital: '', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 0, flag: 'https://restcountries.eu/data/bvt.svg', currency: 'Norwegian krone', }, { name: 'Brazil', capital: 'Brasília', languages: ['Portuguese'], population: 206135893, flag: 'https://restcountries.eu/data/bra.svg', currency: 'Brazilian real', }, { name: 'British Indian Ocean Territory', capital: 'Diego Garcia', languages: ['English'], population: 3000, flag: 'https://restcountries.eu/data/iot.svg', currency: 'United States dollar', }, { name: 'United States Minor Outlying Islands', capital: '', languages: ['English'], population: 300, flag: 'https://restcountries.eu/data/umi.svg', currency: 'United States Dollar', }, { name: 'Virgin Islands (British)', capital: 'Road Town', languages: ['English'], population: 28514, flag: 'https://restcountries.eu/data/vgb.svg', currency: '[D]', }, { name: 'Virgin Islands (U.S.)', capital: 'Charlotte Amalie', languages: ['English'], population: 114743, flag: 'https://restcountries.eu/data/vir.svg', currency: 'United States dollar', }, { name: 'Brunei Darussalam', capital: 'Bandar Seri Begawan', languages: ['Malay'], population: 411900, flag: 'https://restcountries.eu/data/brn.svg', currency: 'Brunei dollar', }, { name: 'Bulgaria', capital: 'Sofia', languages: ['Bulgarian'], population: 7153784, flag: 'https://restcountries.eu/data/bgr.svg', currency: 'Bulgarian lev', }, { name: 'Burkina Faso', capital: 'Ouagadougou', languages: ['French', 'Fula'], population: 19034397, flag: 'https://restcountries.eu/data/bfa.svg', currency: 'West African CFA franc', }, { name: 'Burundi', capital: 'Bujumbura', languages: ['French', 'Kirundi'], population: 10114505, flag: 'https://restcountries.eu/data/bdi.svg', currency: 'Burundian franc', }, { name: 'Cambodia', capital: 'Phnom Penh', languages: ['Khmer'], population: 15626444, flag: 'https://restcountries.eu/data/khm.svg', currency: 'Cambodian riel', }, { name: 'Cameroon', capital: 'Yaoundé', languages: ['English', 'French'], population: 22709892, flag: 'https://restcountries.eu/data/cmr.svg', currency: 'Central African CFA franc', }, { name: 'Canada', capital: 'Ottawa', languages: ['English', 'French'], population: 36155487, flag: 'https://restcountries.eu/data/can.svg', currency: 'Canadian dollar', }, { name: 'Cabo Verde', capital: 'Praia', languages: ['Portuguese'], population: 531239, flag: 'https://restcountries.eu/data/cpv.svg', currency: 'Cape Verdean escudo', }, { name: 'Cayman Islands', capital: 'George Town', languages: ['English'], population: 58238, flag: 'https://restcountries.eu/data/cym.svg', currency: 'Cayman Islands dollar', }, { name: 'Central African Republic', capital: 'Bangui', languages: ['French', 'Sango'], population: 4998000, flag: 'https://restcountries.eu/data/caf.svg', currency: 'Central African CFA franc', }, { name: 'Chad', capital: "N'Djamena", languages: ['French', 'Arabic'], population: 14497000, flag: 'https://restcountries.eu/data/tcd.svg', currency: 'Central African CFA franc', }, { name: 'Chile', capital: 'Santiago', languages: ['Spanish'], population: 18191900, flag: 'https://restcountries.eu/data/chl.svg', currency: 'Chilean peso', }, { name: 'China', capital: 'Beijing', languages: ['Chinese'], population: 1377422166, flag: 'https://restcountries.eu/data/chn.svg', currency: 'Chinese yuan', }, { name: 'Christmas Island', capital: 'Flying Fish Cove', languages: ['English'], population: 2072, flag: 'https://restcountries.eu/data/cxr.svg', currency: 'Australian dollar', }, { name: 'Cocos (Keeling) Islands', capital: 'West Island', languages: ['English'], population: 550, flag: 'https://restcountries.eu/data/cck.svg', currency: 'Australian dollar', }, { name: 'Colombia', capital: 'Bogotá', languages: ['Spanish'], population: 48759958, flag: 'https://restcountries.eu/data/col.svg', currency: 'Colombian peso', }, { name: 'Comoros', capital: 'Moroni', languages: ['Arabic', 'French'], population: 806153, flag: 'https://restcountries.eu/data/com.svg', currency: 'Comorian franc', }, { name: 'Congo', capital: 'Brazzaville', languages: ['French', 'Lingala'], population: 4741000, flag: 'https://restcountries.eu/data/cog.svg', currency: 'Central African CFA franc', }, { name: 'Congo (Democratic Republic of the)', capital: 'Kinshasa', languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], population: 85026000, flag: 'https://restcountries.eu/data/cod.svg', currency: 'Congolese franc', }, { name: 'Cook Islands', capital: 'Avarua', languages: ['English'], population: 18100, flag: 'https://restcountries.eu/data/cok.svg', currency: 'New Zealand dollar', }, { name: 'Costa Rica', capital: 'San José', languages: ['Spanish'], population: 4890379, flag: 'https://restcountries.eu/data/cri.svg', currency: 'Costa Rican colón', }, { name: 'Croatia', capital: 'Zagreb', languages: ['Croatian'], population: 4190669, flag: 'https://restcountries.eu/data/hrv.svg', currency: 'Croatian kuna', }, { name: 'Cuba', capital: 'Havana', languages: ['Spanish'], population: 11239004, flag: 'https://restcountries.eu/data/cub.svg', currency: 'Cuban convertible peso', }, { name: 'Curaçao', capital: 'Willemstad', languages: ['Dutch', '(Eastern) Punjabi', 'English'], population: 154843, flag: 'https://restcountries.eu/data/cuw.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Cyprus', capital: 'Nicosia', languages: ['Greek (modern)', 'Turkish', 'Armenian'], population: 847000, flag: 'https://restcountries.eu/data/cyp.svg', currency: 'Euro', }, { name: 'Czech Republic', capital: 'Prague', languages: ['Czech', 'Slovak'], population: 10558524, flag: 'https://restcountries.eu/data/cze.svg', currency: 'Czech koruna', }, { name: 'Denmark', capital: 'Copenhagen', languages: ['Danish'], population: 5717014, flag: 'https://restcountries.eu/data/dnk.svg', currency: 'Danish krone', }, { name: 'Djibouti', capital: 'Djibouti', languages: ['French', 'Arabic'], population: 900000, flag: 'https://restcountries.eu/data/dji.svg', currency: 'Djiboutian franc', }, { name: 'Dominica', capital: 'Roseau', languages: ['English'], population: 71293, flag: 'https://restcountries.eu/data/dma.svg', currency: 'East Caribbean dollar', }, { name: 'Dominican Republic', capital: 'Santo Domingo', languages: ['Spanish'], population: 10075045, flag: 'https://restcountries.eu/data/dom.svg', currency: 'Dominican peso', }, { name: 'Ecuador', capital: 'Quito', languages: ['Spanish'], population: 16545799, flag: 'https://restcountries.eu/data/ecu.svg', currency: 'United States dollar', }, { name: 'Egypt', capital: 'Cairo', languages: ['Arabic'], population: 91290000, flag: 'https://restcountries.eu/data/egy.svg', currency: 'Egyptian pound', }, { name: 'El Salvador', capital: 'San Salvador', languages: ['Spanish'], population: 6520675, flag: 'https://restcountries.eu/data/slv.svg', currency: 'United States dollar', }, { name: 'Equatorial Guinea', capital: 'Malabo', languages: ['Spanish', 'French'], population: 1222442, flag: 'https://restcountries.eu/data/gnq.svg', currency: 'Central African CFA franc', }, { name: 'Eritrea', capital: 'Asmara', languages: ['Tigrinya', 'Arabic', 'English'], population: 5352000, flag: 'https://restcountries.eu/data/eri.svg', currency: 'Eritrean nakfa', }, { name: 'Estonia', capital: 'Tallinn', languages: ['Estonian'], population: 1315944, flag: 'https://restcountries.eu/data/est.svg', currency: 'Euro', }, { name: 'Ethiopia', capital: 'Addis Ababa', languages: ['Amharic'], population: 92206005, flag: 'https://restcountries.eu/data/eth.svg', currency: 'Ethiopian birr', }, { name: 'Falkland Islands (Malvinas)', capital: 'Stanley', languages: ['English'], population: 2563, flag: 'https://restcountries.eu/data/flk.svg', currency: 'Falkland Islands pound', }, { name: 'Faroe Islands', capital: 'Tórshavn', languages: ['Faroese'], population: 49376, flag: 'https://restcountries.eu/data/fro.svg', currency: 'Danish krone', }, { name: 'Fiji', capital: 'Suva', languages: ['English', 'Fijian', 'Hindi', 'Urdu'], population: 867000, flag: 'https://restcountries.eu/data/fji.svg', currency: 'Fijian dollar', }, { name: 'Finland', capital: 'Helsinki', languages: ['Finnish', 'Swedish'], population: 5491817, flag: 'https://restcountries.eu/data/fin.svg', currency: 'Euro', }, { name: 'France', capital: 'Paris', languages: ['French'], population: 66710000, flag: 'https://restcountries.eu/data/fra.svg', currency: 'Euro', }, { name: 'French Guiana', capital: 'Cayenne', languages: ['French'], population: 254541, flag: 'https://restcountries.eu/data/guf.svg', currency: 'Euro', }, { name: 'French Polynesia', capital: 'Papeetē', languages: ['French'], population: 271800, flag: 'https://restcountries.eu/data/pyf.svg', currency: 'CFP franc', }, { name: 'French Southern Territories', capital: 'Port-aux-Français', languages: ['French'], population: 140, flag: 'https://restcountries.eu/data/atf.svg', currency: 'Euro', }, { name: 'Gabon', capital: 'Libreville', languages: ['French'], population: 1802278, flag: 'https://restcountries.eu/data/gab.svg', currency: 'Central African CFA franc', }, { name: 'Gambia', capital: 'Banjul', languages: ['English'], population: 1882450, flag: 'https://restcountries.eu/data/gmb.svg', currency: 'Gambian dalasi', }, { name: 'Georgia', capital: 'Tbilisi', languages: ['Georgian'], population: 3720400, flag: 'https://restcountries.eu/data/geo.svg', currency: 'Georgian Lari', }, { name: 'Germany', capital: 'Berlin', languages: ['German'], population: 81770900, flag: 'https://restcountries.eu/data/deu.svg', currency: 'Euro', }, { name: 'Ghana', capital: 'Accra', languages: ['English'], population: 27670174, flag: 'https://restcountries.eu/data/gha.svg', currency: 'Ghanaian cedi', }, { name: 'Gibraltar', capital: 'Gibraltar', languages: ['English'], population: 33140, flag: 'https://restcountries.eu/data/gib.svg', currency: 'Gibraltar pound', }, { name: 'Greece', capital: 'Athens', languages: ['Greek (modern)'], population: 10858018, flag: 'https://restcountries.eu/data/grc.svg', currency: 'Euro', }, { name: 'Greenland', capital: 'Nuuk', languages: ['Kalaallisut'], population: 55847, flag: 'https://restcountries.eu/data/grl.svg', currency: 'Danish krone', }, { name: 'Grenada', capital: "St. George's", languages: ['English'], population: 103328, flag: 'https://restcountries.eu/data/grd.svg', currency: 'East Caribbean dollar', }, { name: 'Guadeloupe', capital: 'Basse-Terre', languages: ['French'], population: 400132, flag: 'https://restcountries.eu/data/glp.svg', currency: 'Euro', }, { name: 'Guam', capital: 'Hagåtña', languages: ['English', 'Chamorro', 'Spanish'], population: 184200, flag: 'https://restcountries.eu/data/gum.svg', currency: 'United States dollar', }, { name: 'Guatemala', capital: 'Guatemala City', languages: ['Spanish'], population: 16176133, flag: 'https://restcountries.eu/data/gtm.svg', currency: 'Guatemalan quetzal', }, { name: 'Guernsey', capital: 'St. Peter Port', languages: ['English', 'French'], population: 62999, flag: 'https://restcountries.eu/data/ggy.svg', currency: 'British pound', }, { name: 'Guinea', capital: 'Conakry', languages: ['French', 'Fula'], population: 12947000, flag: 'https://restcountries.eu/data/gin.svg', currency: 'Guinean franc', }, { name: 'Guinea-Bissau', capital: 'Bissau', languages: ['Portuguese'], population: 1547777, flag: 'https://restcountries.eu/data/gnb.svg', currency: 'West African CFA franc', }, { name: 'Guyana', capital: 'Georgetown', languages: ['English'], population: 746900, flag: 'https://restcountries.eu/data/guy.svg', currency: 'Guyanese dollar', }, { name: 'Haiti', capital: 'Port-au-Prince', languages: ['French', 'Haitian'], population: 11078033, flag: 'https://restcountries.eu/data/hti.svg', currency: 'Haitian gourde', }, { name: 'Heard Island and McDonald Islands', capital: '', languages: ['English'], population: 0, flag: 'https://restcountries.eu/data/hmd.svg', currency: 'Australian dollar', }, { name: 'Holy See', capital: 'Rome', languages: ['Latin', 'Italian', 'French', 'German'], population: 451, flag: 'https://restcountries.eu/data/vat.svg', currency: 'Euro', }, { name: 'Honduras', capital: 'Tegucigalpa', languages: ['Spanish'], population: 8576532, flag: 'https://restcountries.eu/data/hnd.svg', currency: 'Honduran lempira', }, { name: 'Hong Kong', capital: 'City of Victoria', languages: ['English', 'Chinese'], population: 7324300, flag: 'https://restcountries.eu/data/hkg.svg', currency: 'Hong Kong dollar', }, { name: 'Hungary', capital: 'Budapest', languages: ['Hungarian'], population: 9823000, flag: 'https://restcountries.eu/data/hun.svg', currency: 'Hungarian forint', }, { name: 'Iceland', capital: 'Reykjavík', languages: ['Icelandic'], population: 334300, flag: 'https://restcountries.eu/data/isl.svg', currency: 'Icelandic króna', }, { name: 'India', capital: 'New Delhi', languages: ['Hindi', 'English'], population: 1295210000, flag: 'https://restcountries.eu/data/ind.svg', currency: 'Indian rupee', }, { name: 'Indonesia', capital: 'Jakarta', languages: ['Indonesian'], population: 258705000, flag: 'https://restcountries.eu/data/idn.svg', currency: 'Indonesian rupiah', }, { name: "Côte d'Ivoire", capital: 'Yamoussoukro', languages: ['French'], population: 22671331, flag: 'https://restcountries.eu/data/civ.svg', currency: 'West African CFA franc', }, { name: 'Iran (Islamic Republic of)', capital: 'Tehran', languages: ['Persian (Farsi)'], population: 79369900, flag: 'https://restcountries.eu/data/irn.svg', currency: 'Iranian rial', }, { name: 'Iraq', capital: 'Baghdad', languages: ['Arabic', 'Kurdish'], population: 37883543, flag: 'https://restcountries.eu/data/irq.svg', currency: 'Iraqi dinar', }, { name: 'Ireland', capital: 'Dublin', languages: ['Irish', 'English'], population: 6378000, flag: 'https://restcountries.eu/data/irl.svg', currency: 'Euro', }, { name: 'Isle of Man', capital: 'Douglas', languages: ['English', 'Manx'], population: 84497, flag: 'https://restcountries.eu/data/imn.svg', currency: 'British pound', }, { name: 'Israel', capital: 'Jerusalem', languages: ['Hebrew (modern)', 'Arabic'], population: 8527400, flag: 'https://restcountries.eu/data/isr.svg', currency: 'Israeli new shekel', }, { name: 'Italy', capital: 'Rome', languages: ['Italian'], population: 60665551, flag: 'https://restcountries.eu/data/ita.svg', currency: 'Euro', }, { name: 'Jamaica', capital: 'Kingston', languages: ['English'], population: 2723246, flag: 'https://restcountries.eu/data/jam.svg', currency: 'Jamaican dollar', }, { name: 'Japan', capital: 'Tokyo', languages: ['Japanese'], population: 126960000, flag: 'https://restcountries.eu/data/jpn.svg', currency: 'Japanese yen', }, { name: 'Jersey', capital: 'Saint Helier', languages: ['English', 'French'], population: 100800, flag: 'https://restcountries.eu/data/jey.svg', currency: 'British pound', }, { name: 'Jordan', capital: 'Amman', languages: ['Arabic'], population: 9531712, flag: 'https://restcountries.eu/data/jor.svg', currency: 'Jordanian dinar', }, { name: 'Kazakhstan', capital: 'Astana', languages: ['Kazakh', 'Russian'], population: 17753200, flag: 'https://restcountries.eu/data/kaz.svg', currency: 'Kazakhstani tenge', }, { name: 'Kenya', capital: 'Nairobi', languages: ['English', 'Swahili'], population: 47251000, flag: 'https://restcountries.eu/data/ken.svg', currency: 'Kenyan shilling', }, { name: 'Kiribati', capital: 'South Tarawa', languages: ['English'], population: 113400, flag: 'https://restcountries.eu/data/kir.svg', currency: 'Australian dollar', }, { name: 'Kuwait', capital: 'Kuwait City', languages: ['Arabic'], population: 4183658, flag: 'https://restcountries.eu/data/kwt.svg', currency: 'Kuwaiti dinar', }, { name: 'Kyrgyzstan', capital: 'Bishkek', languages: ['Kyrgyz', 'Russian'], population: 6047800, flag: 'https://restcountries.eu/data/kgz.svg', currency: 'Kyrgyzstani som', }, { name: "Lao People's Democratic Republic", capital: 'Vientiane', languages: ['Lao'], population: 6492400, flag: 'https://restcountries.eu/data/lao.svg', currency: 'Lao kip', }, { name: 'Latvia', capital: 'Riga', languages: ['Latvian'], population: 1961600, flag: 'https://restcountries.eu/data/lva.svg', currency: 'Euro', }, { name: 'Lebanon', capital: 'Beirut', languages: ['Arabic', 'French'], population: 5988000, flag: 'https://restcountries.eu/data/lbn.svg', currency: 'Lebanese pound', }, { name: 'Lesotho', capital: 'Maseru', languages: ['English', 'Southern Sotho'], population: 1894194, flag: 'https://restcountries.eu/data/lso.svg', currency: 'Lesotho loti', }, { name: 'Liberia', capital: 'Monrovia', languages: ['English'], population: 4615000, flag: 'https://restcountries.eu/data/lbr.svg', currency: 'Liberian dollar', }, { name: 'Libya', capital: 'Tripoli', languages: ['Arabic'], population: 6385000, flag: 'https://restcountries.eu/data/lby.svg', currency: 'Libyan dinar', }, { name: 'Liechtenstein', capital: 'Vaduz', languages: ['German'], population: 37623, flag: 'https://restcountries.eu/data/lie.svg', currency: 'Swiss franc', }, { name: 'Lithuania', capital: 'Vilnius', languages: ['Lithuanian'], population: 2872294, flag: 'https://restcountries.eu/data/ltu.svg', currency: 'Euro', }, { name: 'Luxembourg', capital: 'Luxembourg', languages: ['French', 'German', 'Luxembourgish'], population: 576200, flag: 'https://restcountries.eu/data/lux.svg', currency: 'Euro', }, { name: 'Macao', capital: '', languages: ['Chinese', 'Portuguese'], population: 649100, flag: 'https://restcountries.eu/data/mac.svg', currency: 'Macanese pataca', }, { name: 'Macedonia (the former Yugoslav Republic of)', capital: 'Skopje', languages: ['Macedonian'], population: 2058539, flag: 'https://restcountries.eu/data/mkd.svg', currency: 'Macedonian denar', }, { name: 'Madagascar', capital: 'Antananarivo', languages: ['French', 'Malagasy'], population: 22434363, flag: 'https://restcountries.eu/data/mdg.svg', currency: 'Malagasy ariary', }, { name: 'Malawi', capital: 'Lilongwe', languages: ['English', 'Chichewa'], population: 16832910, flag: 'https://restcountries.eu/data/mwi.svg', currency: 'Malawian kwacha', }, { name: 'Malaysia', capital: 'Kuala Lumpur', languages: ['Malaysian'], population: 31405416, flag: 'https://restcountries.eu/data/mys.svg', currency: 'Malaysian ringgit', }, { name: 'Maldives', capital: 'Malé', languages: ['Divehi'], population: 344023, flag: 'https://restcountries.eu/data/mdv.svg', currency: 'Maldivian rufiyaa', }, { name: 'Mali', capital: 'Bamako', languages: ['French'], population: 18135000, flag: 'https://restcountries.eu/data/mli.svg', currency: 'West African CFA franc', }, { name: 'Malta', capital: 'Valletta', languages: ['Maltese', 'English'], population: 425384, flag: 'https://restcountries.eu/data/mlt.svg', currency: 'Euro', }, { name: 'Marshall Islands', capital: 'Majuro', languages: ['English', 'Marshallese'], population: 54880, flag: 'https://restcountries.eu/data/mhl.svg', currency: 'United States dollar', }, { name: 'Martinique', capital: 'Fort-de-France', languages: ['French'], population: 378243, flag: 'https://restcountries.eu/data/mtq.svg', currency: 'Euro', }, { name: 'Mauritania', capital: 'Nouakchott', languages: ['Arabic'], population: 3718678, flag: 'https://restcountries.eu/data/mrt.svg', currency: 'Mauritanian ouguiya', }, { name: 'Mauritius', capital: 'Port Louis', languages: ['English'], population: 1262879, flag: 'https://restcountries.eu/data/mus.svg', currency: 'Mauritian rupee', }, { name: 'Mayotte', capital: 'Mamoudzou', languages: ['French'], population: 226915, flag: 'https://restcountries.eu/data/myt.svg', currency: 'Euro', }, { name: 'Mexico', capital: 'Mexico City', languages: ['Spanish'], population: 122273473, flag: 'https://restcountries.eu/data/mex.svg', currency: 'Mexican peso', }, { name: 'Micronesia (Federated States of)', capital: 'Palikir', languages: ['English'], population: 102800, flag: 'https://restcountries.eu/data/fsm.svg', currency: '[D]', }, { name: 'Moldova (Republic of)', capital: 'Chișinău', languages: ['Romanian'], population: 3553100, flag: 'https://restcountries.eu/data/mda.svg', currency: 'Moldovan leu', }, { name: 'Monaco', capital: 'Monaco', languages: ['French'], population: 38400, flag: 'https://restcountries.eu/data/mco.svg', currency: 'Euro', }, { name: 'Mongolia', capital: 'Ulan Bator', languages: ['Mongolian'], population: 3093100, flag: 'https://restcountries.eu/data/mng.svg', currency: 'Mongolian tögrög', }, { name: 'Montenegro', capital: 'Podgorica', languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], population: 621810, flag: 'https://restcountries.eu/data/mne.svg', currency: 'Euro', }, { name: 'Montserrat', capital: 'Plymouth', languages: ['English'], population: 4922, flag: 'https://restcountries.eu/data/msr.svg', currency: 'East Caribbean dollar', }, { name: 'Morocco', capital: 'Rabat', languages: ['Arabic'], population: 33337529, flag: 'https://restcountries.eu/data/mar.svg', currency: 'Moroccan dirham', }, { name: 'Mozambique', capital: 'Maputo', languages: ['Portuguese'], population: 26423700, flag: 'https://restcountries.eu/data/moz.svg', currency: 'Mozambican metical', }, { name: 'Myanmar', capital: 'Naypyidaw', languages: ['Burmese'], population: 51419420, flag: 'https://restcountries.eu/data/mmr.svg', currency: 'Burmese kyat', }, { name: 'Namibia', capital: 'Windhoek', languages: ['English', 'Afrikaans'], population: 2324388, flag: 'https://restcountries.eu/data/nam.svg', currency: 'Namibian dollar', }, { name: 'Nauru', capital: 'Yaren', languages: ['English', 'Nauruan'], population: 10084, flag: 'https://restcountries.eu/data/nru.svg', currency: 'Australian dollar', }, { name: 'Nepal', capital: 'Kathmandu', languages: ['Nepali'], population: 28431500, flag: 'https://restcountries.eu/data/npl.svg', currency: 'Nepalese rupee', }, { name: 'Netherlands', capital: 'Amsterdam', languages: ['Dutch'], population: 17019800, flag: 'https://restcountries.eu/data/nld.svg', currency: 'Euro', }, { name: 'New Caledonia', capital: 'Nouméa', languages: ['French'], population: 268767, flag: 'https://restcountries.eu/data/ncl.svg', currency: 'CFP franc', }, { name: 'New Zealand', capital: 'Wellington', languages: ['English', 'Māori'], population: 4697854, flag: 'https://restcountries.eu/data/nzl.svg', currency: 'New Zealand dollar', }, { name: 'Nicaragua', capital: 'Managua', languages: ['Spanish'], population: 6262703, flag: 'https://restcountries.eu/data/nic.svg', currency: 'Nicaraguan córdoba', }, { name: 'Niger', capital: 'Niamey', languages: ['French'], population: 20715000, flag: 'https://restcountries.eu/data/ner.svg', currency: 'West African CFA franc', }, { name: 'Nigeria', capital: 'Abuja', languages: ['English'], population: 186988000, flag: 'https://restcountries.eu/data/nga.svg', currency: 'Nigerian naira', }, { name: 'Niue', capital: 'Alofi', languages: ['English'], population: 1470, flag: 'https://restcountries.eu/data/niu.svg', currency: 'New Zealand dollar', }, { name: 'Norfolk Island', capital: 'Kingston', languages: ['English'], population: 2302, flag: 'https://restcountries.eu/data/nfk.svg', currency: 'Australian dollar', }, { name: "Korea (Democratic People's Republic of)", capital: 'Pyongyang', languages: ['Korean'], population: 25281000, flag: 'https://restcountries.eu/data/prk.svg', currency: 'North Korean won', }, { name: 'Northern Mariana Islands', capital: 'Saipan', languages: ['English', 'Chamorro'], population: 56940, flag: 'https://restcountries.eu/data/mnp.svg', currency: 'United States dollar', }, { name: 'Norway', capital: 'Oslo', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 5223256, flag: 'https://restcountries.eu/data/nor.svg', currency: 'Norwegian krone', }, { name: 'Oman', capital: 'Muscat', languages: ['Arabic'], population: 4420133, flag: 'https://restcountries.eu/data/omn.svg', currency: 'Omani rial', }, { name: 'Pakistan', capital: 'Islamabad', languages: ['English', 'Urdu'], population: 194125062, flag: 'https://restcountries.eu/data/pak.svg', currency: 'Pakistani rupee', }, { name: 'Palau', capital: 'Ngerulmud', languages: ['English'], population: 17950, flag: 'https://restcountries.eu/data/plw.svg', currency: '[E]', }, { name: 'Palestine, State of', capital: 'Ramallah', languages: ['Arabic'], population: 4682467, flag: 'https://restcountries.eu/data/pse.svg', currency: 'Israeli new sheqel', }, { name: 'Panama', capital: 'Panama City', languages: ['Spanish'], population: 3814672, flag: 'https://restcountries.eu/data/pan.svg', currency: 'Panamanian balboa', }, { name: 'Papua New Guinea', capital: 'Port Moresby', languages: ['English'], population: 8083700, flag: 'https://restcountries.eu/data/png.svg', currency: 'Papua New Guinean kina', }, { name: 'Paraguay', capital: 'Asunción', languages: ['Spanish', 'Guaraní'], population: 6854536, flag: 'https://restcountries.eu/data/pry.svg', currency: 'Paraguayan guaraní', }, { name: 'Peru', capital: 'Lima', languages: ['Spanish'], population: 31488700, flag: 'https://restcountries.eu/data/per.svg', currency: 'Peruvian sol', }, { name: 'Philippines', capital: 'Manila', languages: ['English'], population: 103279800, flag: 'https://restcountries.eu/data/phl.svg', currency: 'Philippine peso', }, { name: 'Pitcairn', capital: 'Adamstown', languages: ['English'], population: 56, flag: 'https://restcountries.eu/data/pcn.svg', currency: 'New Zealand dollar', }, { name: 'Poland', capital: 'Warsaw', languages: ['Polish'], population: 38437239, flag: 'https://restcountries.eu/data/pol.svg', currency: 'Polish złoty', }, { name: 'Portugal', capital: 'Lisbon', languages: ['Portuguese'], population: 10374822, flag: 'https://restcountries.eu/data/prt.svg', currency: 'Euro', }, { name: 'Puerto Rico', capital: 'San Juan', languages: ['Spanish', 'English'], population: 3474182, flag: 'https://restcountries.eu/data/pri.svg', currency: 'United States dollar', }, { name: 'Qatar', capital: 'Doha', languages: ['Arabic'], population: 2587564, flag: 'https://restcountries.eu/data/qat.svg', currency: 'Qatari riyal', }, { name: 'Republic of Kosovo', capital: 'Pristina', languages: ['Albanian', 'Serbian'], population: 1733842, flag: 'https://restcountries.eu/data/kos.svg', currency: 'Euro', }, { name: 'Réunion', capital: 'Saint-Denis', languages: ['French'], population: 840974, flag: 'https://restcountries.eu/data/reu.svg', currency: 'Euro', }, { name: 'Romania', capital: 'Bucharest', languages: ['Romanian'], population: 19861408, flag: 'https://restcountries.eu/data/rou.svg', currency: 'Romanian leu', }, { name: 'Russian Federation', capital: 'Moscow', languages: ['Russian'], population: 146599183, flag: 'https://restcountries.eu/data/rus.svg', currency: 'Russian ruble', }, { name: 'Rwanda', capital: 'Kigali', languages: ['Kinyarwanda', 'English', 'French'], population: 11553188, flag: 'https://restcountries.eu/data/rwa.svg', currency: 'Rwandan franc', }, { name: 'Saint Barthélemy', capital: 'Gustavia', languages: ['French'], population: 9417, flag: 'https://restcountries.eu/data/blm.svg', currency: 'Euro', }, { name: 'Saint Helena, Ascension and Tristan da Cunha', capital: 'Jamestown', languages: ['English'], population: 4255, flag: 'https://restcountries.eu/data/shn.svg', currency: 'Saint Helena pound', }, { name: 'Saint Kitts and Nevis', capital: 'Basseterre', languages: ['English'], population: 46204, flag: 'https://restcountries.eu/data/kna.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Lucia', capital: 'Castries', languages: ['English'], population: 186000, flag: 'https://restcountries.eu/data/lca.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Martin (French part)', capital: 'Marigot', languages: ['English', 'French', 'Dutch'], population: 36979, flag: 'https://restcountries.eu/data/maf.svg', currency: 'Euro', }, { name: 'Saint Pierre and Miquelon', capital: 'Saint-Pierre', languages: ['French'], population: 6069, flag: 'https://restcountries.eu/data/spm.svg', currency: 'Euro', }, { name: 'Saint Vincent and the Grenadines', capital: 'Kingstown', languages: ['English'], population: 109991, flag: 'https://restcountries.eu/data/vct.svg', currency: 'East Caribbean dollar', }, { name: 'Samoa', capital: 'Apia', languages: ['Samoan', 'English'], population: 194899, flag: 'https://restcountries.eu/data/wsm.svg', currency: 'Samoan tālā', }, { name: 'San Marino', capital: 'City of San Marino', languages: ['Italian'], population: 33005, flag: 'https://restcountries.eu/data/smr.svg', currency: 'Euro', }, { name: 'Sao Tome and Principe', capital: 'São Tomé', languages: ['Portuguese'], population: 187356, flag: 'https://restcountries.eu/data/stp.svg', currency: 'São Tomé and Príncipe dobra', }, { name: 'Saudi Arabia', capital: 'Riyadh', languages: ['Arabic'], population: 32248200, flag: 'https://restcountries.eu/data/sau.svg', currency: 'Saudi riyal', }, { name: 'Senegal', capital: 'Dakar', languages: ['French'], population: 14799859, flag: 'https://restcountries.eu/data/sen.svg', currency: 'West African CFA franc', }, { name: 'Serbia', capital: 'Belgrade', languages: ['Serbian'], population: 7076372, flag: 'https://restcountries.eu/data/srb.svg', currency: 'Serbian dinar', }, { name: 'Seychelles', capital: 'Victoria', languages: ['French', 'English'], population: 91400, flag: 'https://restcountries.eu/data/syc.svg', currency: 'Seychellois rupee', }, { name: 'Sierra Leone', capital: 'Freetown', languages: ['English'], population: 7075641, flag: 'https://restcountries.eu/data/sle.svg', currency: 'Sierra Leonean leone', }, { name: 'Singapore', capital: 'Singapore', languages: ['English', 'Malay', 'Tamil', 'Chinese'], population: 5535000, flag: 'https://restcountries.eu/data/sgp.svg', currency: 'Brunei dollar', }, { name: 'Sint Maarten (Dutch part)', capital: 'Philipsburg', languages: ['Dutch', 'English'], population: 38247, flag: 'https://restcountries.eu/data/sxm.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Slovakia', capital: 'Bratislava', languages: ['Slovak'], population: 5426252, flag: 'https://restcountries.eu/data/svk.svg', currency: 'Euro', }, { name: 'Slovenia', capital: 'Ljubljana', languages: ['Slovene'], population: 2064188, flag: 'https://restcountries.eu/data/svn.svg', currency: 'Euro', }, { name: 'Solomon Islands', capital: 'Honiara', languages: ['English'], population: 642000, flag: 'https://restcountries.eu/data/slb.svg', currency: 'Solomon Islands dollar', }, { name: 'Somalia', capital: 'Mogadishu', languages: ['Somali', 'Arabic'], population: 11079000, flag: 'https://restcountries.eu/data/som.svg', currency: 'Somali shilling', }, { name: 'South Africa', capital: 'Pretoria', languages: [ 'Afrikaans', 'English', 'Southern Ndebele', 'Southern Sotho', 'Swati', 'Tswana', 'Tsonga', 'Venda', 'Xhosa', 'Zulu', ], population: 55653654, flag: 'https://restcountries.eu/data/zaf.svg', currency: 'South African rand', }, { name: 'South Georgia and the South Sandwich Islands', capital: 'King Edward Point', languages: ['English'], population: 30, flag: 'https://restcountries.eu/data/sgs.svg', currency: 'British pound', }, { name: 'Korea (Republic of)', capital: 'Seoul', languages: ['Korean'], population: 50801405, flag: 'https://restcountries.eu/data/kor.svg', currency: 'South Korean won', }, { name: 'South Sudan', capital: 'Juba', languages: ['English'], population: 12131000, flag: 'https://restcountries.eu/data/ssd.svg', currency: 'South Sudanese pound', }, { name: 'Spain', capital: 'Madrid', languages: ['Spanish'], population: 46438422, flag: 'https://restcountries.eu/data/esp.svg', currency: 'Euro', }, { name: 'Sri Lanka', capital: 'Colombo', languages: ['Sinhalese', 'Tamil'], population: 20966000, flag: 'https://restcountries.eu/data/lka.svg', currency: 'Sri Lankan rupee', }, { name: 'Sudan', capital: 'Khartoum', languages: ['Arabic', 'English'], population: 39598700, flag: 'https://restcountries.eu/data/sdn.svg', currency: 'Sudanese pound', }, { name: 'Suriname', capital: 'Paramaribo', languages: ['Dutch'], population: 541638, flag: 'https://restcountries.eu/data/sur.svg', currency: 'Surinamese dollar', }, { name: 'Svalbard and Jan Mayen', capital: 'Longyearbyen', languages: ['Norwegian'], population: 2562, flag: 'https://restcountries.eu/data/sjm.svg', currency: 'Norwegian krone', }, { name: 'Swaziland', capital: 'Lobamba', languages: ['English', 'Swati'], population: 1132657, flag: 'https://restcountries.eu/data/swz.svg', currency: 'Swazi lilangeni', }, { name: 'Sweden', capital: 'Stockholm', languages: ['Swedish'], population: 9894888, flag: 'https://restcountries.eu/data/swe.svg', currency: 'Swedish krona', }, { name: 'Switzerland', capital: 'Bern', languages: ['German', 'French', 'Italian'], population: 8341600, flag: 'https://restcountries.eu/data/che.svg', currency: 'Swiss franc', }, { name: 'Syrian Arab Republic', capital: 'Damascus', languages: ['Arabic'], population: 18564000, flag: 'https://restcountries.eu/data/syr.svg', currency: 'Syrian pound', }, { name: 'Taiwan', capital: 'Taipei', languages: ['Chinese'], population: 23503349, flag: 'https://restcountries.eu/data/twn.svg', currency: 'New Taiwan dollar', }, { name: 'Tajikistan', capital: 'Dushanbe', languages: ['Tajik', 'Russian'], population: 8593600, flag: 'https://restcountries.eu/data/tjk.svg', currency: 'Tajikistani somoni', }, { name: 'Tanzania, United Republic of', capital: 'Dodoma', languages: ['Swahili', 'English'], population: 55155000, flag: 'https://restcountries.eu/data/tza.svg', currency: 'Tanzanian shilling', }, { name: 'Thailand', capital: 'Bangkok', languages: ['Thai'], population: 65327652, flag: 'https://restcountries.eu/data/tha.svg', currency: 'Thai baht', }, { name: 'Timor-Leste', capital: 'Dili', languages: ['Portuguese'], population: 1167242, flag: 'https://restcountries.eu/data/tls.svg', currency: 'United States dollar', }, { name: 'Togo', capital: 'Lomé', languages: ['French'], population: 7143000, flag: 'https://restcountries.eu/data/tgo.svg', currency: 'West African CFA franc', }, { name: 'Tokelau', capital: 'Fakaofo', languages: ['English'], population: 1411, flag: 'https://restcountries.eu/data/tkl.svg', currency: 'New Zealand dollar', }, { name: 'Tonga', capital: "Nuku'alofa", languages: ['English', 'Tonga (Tonga Islands)'], population: 103252, flag: 'https://restcountries.eu/data/ton.svg', currency: 'Tongan paʻanga', }, { name: 'Trinidad and Tobago', capital: 'Port of Spain', languages: ['English'], population: 1349667, flag: 'https://restcountries.eu/data/tto.svg', currency: 'Trinidad and Tobago dollar', }, { name: 'Tunisia', capital: 'Tunis', languages: ['Arabic'], population: 11154400, flag: 'https://restcountries.eu/data/tun.svg', currency: 'Tunisian dinar', }, { name: 'Turkey', capital: 'Ankara', languages: ['Turkish'], population: 78741053, flag: 'https://restcountries.eu/data/tur.svg', currency: 'Turkish lira', }, { name: 'Turkmenistan', capital: 'Ashgabat', languages: ['Turkmen', 'Russian'], population: 4751120, flag: 'https://restcountries.eu/data/tkm.svg', currency: 'Turkmenistan manat', }, { name: 'Turks and Caicos Islands', capital: 'Cockburn Town', languages: ['English'], population: 31458, flag: 'https://restcountries.eu/data/tca.svg', currency: 'United States dollar', }, { name: 'Tuvalu', capital: 'Funafuti', languages: ['English'], population: 10640, flag: 'https://restcountries.eu/data/tuv.svg', currency: 'Australian dollar', }, { name: 'Uganda', capital: 'Kampala', languages: ['English', 'Swahili'], population: 33860700, flag: 'https://restcountries.eu/data/uga.svg', currency: 'Ugandan shilling', }, { name: 'Ukraine', capital: 'Kiev', languages: ['Ukrainian'], population: 42692393, flag: 'https://restcountries.eu/data/ukr.svg', currency: 'Ukrainian hryvnia', }, { name: 'United Arab Emirates', capital: 'Abu Dhabi', languages: ['Arabic'], population: 9856000, flag: 'https://restcountries.eu/data/are.svg', currency: 'United Arab Emirates dirham', }, { name: 'United Kingdom of Great Britain and Northern Ireland', capital: 'London', languages: ['English'], population: 65110000, flag: 'https://restcountries.eu/data/gbr.svg', currency: 'British pound', }, { name: 'United States of America', capital: 'Washington, D.C.', languages: ['English'], population: 323947000, flag: 'https://restcountries.eu/data/usa.svg', currency: 'United States dollar', }, { name: 'Uruguay', capital: 'Montevideo', languages: ['Spanish'], population: 3480222, flag: 'https://restcountries.eu/data/ury.svg', currency: 'Uruguayan peso', }, { name: 'Uzbekistan', capital: 'Tashkent', languages: ['Uzbek', 'Russian'], population: 31576400, flag: 'https://restcountries.eu/data/uzb.svg', currency: "Uzbekistani so'm", }, { name: 'Vanuatu', capital: 'Port Vila', languages: ['Bislama', 'English', 'French'], population: 277500, flag: 'https://restcountries.eu/data/vut.svg', currency: 'Vanuatu vatu', }, { name: 'Venezuela (Bolivarian Republic of)', capital: 'Caracas', languages: ['Spanish'], population: 31028700, flag: 'https://restcountries.eu/data/ven.svg', currency: 'Venezuelan bolívar', }, { name: 'Viet Nam', capital: 'Hanoi', languages: ['Vietnamese'], population: 92700000, flag: 'https://restcountries.eu/data/vnm.svg', currency: 'Vietnamese đồng', }, { name: 'Wallis and Futuna', capital: 'Mata-Utu', languages: ['French'], population: 11750, flag: 'https://restcountries.eu/data/wlf.svg', currency: 'CFP franc', }, { name: 'Western Sahara', capital: 'El Aaiún', languages: ['Spanish'], population: 510713, flag: 'https://restcountries.eu/data/esh.svg', currency: 'Moroccan dirham', }, { name: 'Yemen', capital: "Sana'a", languages: ['Arabic'], population: 27478000, flag: 'https://restcountries.eu/data/yem.svg', currency: 'Yemeni rial', }, { name: 'Zambia', capital: 'Lusaka', languages: ['English'], population: 15933883, flag: 'https://restcountries.eu/data/zmb.svg', currency: 'Zambian kwacha', }, { name: 'Zimbabwe', capital: 'Harare', languages: ['English', 'Shona', 'Northern Ndebele'], population: 14240168, flag: 'https://restcountries.eu/data/zwe.svg', currency: 'Botswana pula', }, ] ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering_boilerplate/src/data/ten_most_highest_populations.js ================================================ export const tenHighestPopulation = [ { country: 'World', population: 7693165599 }, { country: 'China', population: 1377422166 }, { country: 'India', population: 1295210000 }, { country: 'United States of America', population: 323947000 }, { country: 'Indonesia', population: 258705000 }, { country: 'Brazil', population: 206135893 }, { country: 'Pakistan', population: 194125062 }, { country: 'Nigeria', population: 186988000 }, { country: 'Bangladesh', population: 161006790 }, { country: 'Russian Federation', population: 146599183 }, { country: 'Japan', population: 126960000 }, ] ================================================ FILE: 09_Day_Conditional_Rendering/09_conditional_rendering_boilerplate/src/index.js ================================================ // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { render() { const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const Message = ({ message }) => (

    {message}

    ) const Login = () => (

    Please Login

    ) const Welcome = (props) => (

    Welcome to 30 Days Of React

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // TechList Component // class base component class TechList extends React.Component { render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { render() { const { techs, greetPeople, handleTime, loggedIn, handleLogin, message, } = this.props console.log(message) const status = loggedIn ? : return (

    Prerequisite to get started react.js:

    {techs.length === 3 && (

    You have all the prerequisite courses to get started React

    )}
    ) } } // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { state = { loggedIn: false, techs: ['HTML', 'CSS', 'JS'], message: 'Click show time or Greet people to change me', } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return `${month} ${date}, ${year}` } handleTime = () => { let message = this.showDate(new Date()) this.setState({ message }) } greetPeople = () => { let message = 'Welcome to 30 Days Of React Challenge, 2020' this.setState({ message }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } const techs = ['HTML', 'CSS', 'JavaScript'] return (
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure.md ================================================

    30 Days Of React: React Project Folder Structure

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 9](../09_Day_Conditional_Rendering/09_conditional_rendering.md) | [Day 11 >>](../11_Day_Events/11_events.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_10.jpg) - [React Project Folder Structure and File Naming](#react-project-folder-structure-and-file-naming) - [File Naming](#file-naming) - [Folder](#folder) - [Components Folder](#components-folder) - [Fragments](#fragments) - [Exercises](#exercises) - [Exercises:Level 1](#exerciseslevel-1) - [Exercises:Level 2](#exerciseslevel-2) - [Exercises: Level 3](#exercises-level-3) # React Project Folder Structure and File Naming There is no strict way to use a single folder structure or file naming in React project. Most of the time, these kind of choice can be made by a team. Sometimes a company may have a developed guidelines about what code conventions to follow, folder structure and file naming. There is no right or wrong way of structuring a React project but some structures are better than the others for scalability,maintainability, ease of working on files and easy to understand structure. If you like to learn further about folder structure you may check the following articles. - [React Folder Structure by https://www.devaradise.com ](https://www.devaradise.com/react-project-folder-structure) - [React Folder Structure by www.robinwieruch.de ](https://www.robinwieruch.de/react-folder-structure) - [React Folder Structure by Faraz Ahmad](https://dev.to/farazamiruddin/an-opinionated-guide-to-react-folder-structure-file-naming-1l7i) - [React Folder Structure by https://maxrozen.com/](https://maxrozen.com/guidelines-improve-react-app-folder-structure/) I use a mix of different conventions. If you like you can follow it but please stick in a structure which you think makes sense for you. ## File Naming In all my React project, I will use CamelCase file name for all components. I prefer to use descriptive long name. ## Folder I found it easy to put all images, icons and fonts in the assets folder and all CSS style sheets in styles folder. All components will be in the components folder. So far, we have been working on index.js file. We have lots of component on index.js. Today we will move every component to a single file and we will import all the files to App.js. In the process, you will see my folder structure. Currently, we are at src directory. All the folder structure will be inside the src directory. Let's start from the index.js file. In addition to index.js file, let's create an App.js file and move most of the components we had to App.js for the time being. The index.js is your getaway to connect the component with index.html. ```js // src/index.js // index.js import React from 'react' import ReactDOM from 'react-dom' const App = () =>

    Welcome to 30 Days Of React

    const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` In the above snippet of code, we have the App component. Let's create the App component to its own file, App.js ```js // src/App.js import React from 'react const App = () =>

    Welcome to 30 Days Of React

    ``` We have to export the component to import it in another file. We can export it as a default or named export. In one file, we can make one default export and many named exports. First, let's implement it using name export and later in default export. We just add the keyword export before _let_ or _const_ to make a named export. ```js // src/App.js import React from 'react // named export in arrow function export const App = () =>

    Welcome to 30 Days Of React

    ``` Exporting in a function declaration, a regular function ```js // src/App.js import React from 'react // named export in regular function, function declaration export function App () { return

    Welcome to 30 Days Of React

    } ``` Now, let's import the App component from the App.js file to index.js. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' import { App } from './App' const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` We saw a named export and now let's implement it with default export. We can do it in two ways but it is recommended to use the second way if we are exporting components because sometimes we may bind a component with another higher order component. ```js // src/App.js import React from 'react // export default in arrow function export default const App = () =>

    Welcome to 30 Days Of React

    ``` ```js // src/App.js import React from 'react // export default in arrow function export default function App () { return

    Welcome to 30 Days Of React

    } ``` ```js // src/App.js // Recommended for most of the cases import React from 'react const App = () =>

    Welcome to 30 Days Of React

    export default App ``` If a component is exported as default we do not need curly bracket during importing. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' import App from './App' const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` If you remember, we created the following components so far and we have been putting them together. It is not easy to work like this. Now we will move them all components to a separate file. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' import asabenehImage from './images' import { countriesData } from './data/countries' // Header component class Header extends React.Component { render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } } const Country = ({ country: { name, capital, flag, languages, population, currency }, }) => { const formatedCapital = capital.length > 0 ? ( <> Capital: {capital} ) : ( '' ) const formatLanguage = languages.length > 1 ? `Languages` : `Language` return (
    {name}

    {name.toUpperCase()}

    {formatedCapital}

    {formatLanguage}: {languages.join(', ')}

    Population: {population.toLocaleString()}

    Currency: {currency}

    ) } // User Card Component const UserCard = () => (
    asabeneh image

    Asabeneh Yetayeh

    ) // Hexadecimal color generator const hexaColor = () => { let str = '0123456789abcdef' let color = '' for (let i = 0; i < 6; i++) { let index = Math.floor(Math.random() * str.length) color += str[index] } return '#' + color } const HexaColor = () =>
    {hexaColor()}
    const Message = ({ message }) => (

    {message}

    ) const Login = () => (

    Please Login

    ) const Welcome = (props) => (

    Welcome to 30 Days Of React

    ) // A button component const Button = ({ text, onClick, style }) => ( ) // TechList Component // class base component class TechList extends React.Component { render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { render() { const { techs, greetPeople, handleTime, loggedIn, handleLogin, message, } = this.props console.log(message) const status = loggedIn ? : return (

    Prerequisite to get started react.js:

    {techs.length === 3 && (

    You have all the prerequisite courses to get started React

    )}
    ) } } // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 22, color: 'white', margin: '0 auto', } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { state = { loggedIn: false, techs: ['HTML', 'CSS', 'JS'], message: 'Click show time or Greet people to change me', } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return `${month} ${date}, ${year}` } handleTime = () => { let message = this.showDate(new Date()) this.setState({ message }) } greetPeople = () => { let message = 'Welcome to 30 Days Of React Challenge, 2020' this.setState({ message }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } const techs = ['HTML', 'CSS', 'JavaScript'] return (
    {this.state.backgroundColor}
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Components Folder Inside the src directory will pull all the components ```sh src App.js index.js components -auth -Signup.js -Signin.js -Forgotpassword.js -Resetpassord.js header -Header.js footer -Footer.js assets -images -icnons - fonts styles -button.js -button.scss utils -random-id.js -display-time.js -generate-color.js shared -Button.js -InputField.js -TextAreaField.js ``` Let's create components directory inside src and inside components let's create header director. Create Header.js inside the header directory. ```js // src/components/header/Header.js import React from 'react' const Header = (props) => { return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {date}
    ) } export default Header ``` Similar to the Header let's move all the components to their respective files. All the CSS files on index.html will moved into styles folder and after that each part has been split its respective file, try to check the styles folder. ## Fragments Fragments are a way to avoid unnecessary parent element in JSX. Let's implement a fragment. We import fragment from react module. As you can see below, we imported React and fragment together by use a comma separation. ```js import React, { Fragment } from 'react' const Skills = () => { return (
  • HTML
  • CSS
  • JavaScript
  • ) } const RequiredSkills = () => { return (
    ) } ``` It is also possible to just extract the fragment module from React as shown below. ```js import React from 'react' const Skills = () => { return (
  • HTML
  • CSS
  • JavaScript
  • ) } const RequiredSkills = () => { return (
    ) } ``` In latest version of Reacts it also possible to write without extracting or importing using this signs(<> ) ```js import React from 'react' // Recommended const Skills = () => { return ( <>
  • HTML
  • CSS
  • JavaScript
  • ) } const RequiredSkills = () => { return (
    ) } ``` When we make a class-based component we have been using React.Component instead we can just import the component and the code will look more clean. Let's see an example. ```js import React from 'react' // without importing the Component // Not recommended class App extends React.Component { render() { return

    30 Days of React

    } } ``` ```js import React, { Component } from 'react' // This is recommended class App extends Component { render() { return

    30 Days of React

    } } ``` Well done. Time to do some exercises for your brain and muscles. # Exercises ## Exercises:Level 1 1. What is the importance of React Folder Structure and File Naming 2. How do you export file 3. How do you import file 4. Make a component of module and export it as named or default export 5. Make a component or module and import it 6. Change all the components you have to different folder structure ## Exercises:Level 2 1. Make a simple portfolio using the components we have created so far. Implement a dark mode by using the function we wrote on day 8 challenge. ## Exercises: Level 3 Coming 🎉 CONGRATULATIONS ! 🎉 [<< Day 9](../09_Day_Conditional_Rendering/09_conditional_rendering.md) | [Day 11 >>](../11_Day_Events/11_events.md) ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/README.md ================================================ # 30 Days of React App: Day 10 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/App.js ================================================ import React from 'react' import Header from './components/header/Header' import Main from './components/main/Main' import Footer from './components/footer/Footer' import { countriesData } from './data/countries' import asabenehImage from './assets/images/asabeneh.jpg' import { showDate } from './utils/display-date-and-time' class App extends React.Component { state = { loggedIn: false, techs: ['HTML', 'CSS', 'JS'], message: 'Click show time or Greet people to change me', country: countriesData[1], } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } handleTime = () => { let message = showDate(new Date()) this.setState({ message }) } greetPeople = () => { let message = 'Welcome to 30 Days Of React Challenge, 2020' this.setState({ message }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: new Date(), } const techs = ['HTML', 'CSS', 'JavaScript'] const user = { ...data.author, image: asabenehImage } return (
    {this.state.backgroundColor}
    ) } } export default App ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/components/color/HexaColor.js ================================================ import React from 'react' import { hexaColor } from '../../utils/hexadecimal-color-generator' const HexaColor = (props) => { return (
    {hexaColor()}
    ) } HexaColor.propTypes = {} export default HexaColor ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/components/country/Country.js ================================================ import React from 'react' const Country = ({ country: { name, capital, flag, languages, population, currency }, }) => { const formatedCapital = capital.length > 0 ? ( <> Capital: {capital} ) : ( '' ) const formatLanguage = languages.length > 1 ? `Languages` : `Language` return (
    {name}

    {name.toUpperCase()}

    {formatedCapital}

    {formatLanguage}: {languages.join(', ')}

    Population: {population.toLocaleString()}

    Currency: {currency}

    ) } export default Country ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/components/footer/Footer.js ================================================ import React from 'react' const Footer = ({ date }) => { return (

    Copyright {date.getFullYear()}

    ) } export default Footer ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/components/header/Header.js ================================================ import React from 'react' import PropTypes from 'prop-types' import { showDate } from '../../utils/display-date-and-time' const Header = ({ data: { welcome, title, subtitle, author: { firstName, lastName }, date, }, }) => { return (

    {welcome}

    {title}

    {subtitle}

    {firstName} {lastName}

    {showDate(date)}
    ) } export default Header ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/components/main/Main.js ================================================ import React from 'react' import Button from '../shared/Button' import HexaColr from '../color/HexaColor' import Country from '../country/Country' import UserCard from '../user/UserCard' import { buttonStyles } from '../../styles/button-styles' // TechList Component // class base component class TechList extends React.Component { render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } const Message = ({ message }) => (

    {message}

    ) const Login = () => (

    Please Login

    ) const Welcome = (props) => (

    Welcome to 30 Days Of React

    ) // Main Component // Class Component class Main extends React.Component { render() { const { techs, greetPeople, handleTime, loggedIn, handleLogin, message, country, user, } = this.props console.log(message) const status = loggedIn ? : return (

    Prerequisite to get started react.js:

    {techs.length === 3 && (

    You have all the prerequisite courses to get started React

    )}
    ) } } export default Main ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/components/shared/Button.js ================================================ import React from 'react' // A button component const Button = ({ text, onClick, style }) => ( ) export default Button ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/components/user/UserCard.js ================================================ import React from 'react' // User Card Component const UserCard = ({ user: { firstName, lastName, image } }) => (
    asabeneh image

    {firstName} {lastName}

    ) export default UserCard ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/data/countries.js ================================================ export const countriesData = [ { name: 'Afghanistan', capital: 'Kabul', languages: ['Pashto', 'Uzbek', 'Turkmen'], population: 27657145, flag: 'https://restcountries.eu/data/afg.svg', currency: 'Afghan afghani', }, { name: 'Åland Islands', capital: 'Mariehamn', languages: ['Swedish'], population: 28875, flag: 'https://restcountries.eu/data/ala.svg', currency: 'Euro', }, { name: 'Albania', capital: 'Tirana', languages: ['Albanian'], population: 2886026, flag: 'https://restcountries.eu/data/alb.svg', currency: 'Albanian lek', }, { name: 'Algeria', capital: 'Algiers', languages: ['Arabic'], population: 40400000, flag: 'https://restcountries.eu/data/dza.svg', currency: 'Algerian dinar', }, { name: 'American Samoa', capital: 'Pago Pago', languages: ['English', 'Samoan'], population: 57100, flag: 'https://restcountries.eu/data/asm.svg', currency: 'United State Dollar', }, { name: 'Andorra', capital: 'Andorra la Vella', languages: ['Catalan'], population: 78014, flag: 'https://restcountries.eu/data/and.svg', currency: 'Euro', }, { name: 'Angola', capital: 'Luanda', languages: ['Portuguese'], population: 25868000, flag: 'https://restcountries.eu/data/ago.svg', currency: 'Angolan kwanza', }, { name: 'Anguilla', capital: 'The Valley', languages: ['English'], population: 13452, flag: 'https://restcountries.eu/data/aia.svg', currency: 'East Caribbean dollar', }, { name: 'Antarctica', capital: '', languages: ['English', 'Russian'], population: 1000, flag: 'https://restcountries.eu/data/ata.svg', currency: 'Australian dollar', }, { name: 'Antigua and Barbuda', capital: "Saint John's", languages: ['English'], population: 86295, flag: 'https://restcountries.eu/data/atg.svg', currency: 'East Caribbean dollar', }, { name: 'Argentina', capital: 'Buenos Aires', languages: ['Spanish', 'Guaraní'], population: 43590400, flag: 'https://restcountries.eu/data/arg.svg', currency: 'Argentine peso', }, { name: 'Armenia', capital: 'Yerevan', languages: ['Armenian', 'Russian'], population: 2994400, flag: 'https://restcountries.eu/data/arm.svg', currency: 'Armenian dram', }, { name: 'Aruba', capital: 'Oranjestad', languages: ['Dutch', '(Eastern) Punjabi'], population: 107394, flag: 'https://restcountries.eu/data/abw.svg', currency: 'Aruban florin', }, { name: 'Australia', capital: 'Canberra', languages: ['English'], population: 24117360, flag: 'https://restcountries.eu/data/aus.svg', currency: 'Australian dollar', }, { name: 'Austria', capital: 'Vienna', languages: ['German'], population: 8725931, flag: 'https://restcountries.eu/data/aut.svg', currency: 'Euro', }, { name: 'Azerbaijan', capital: 'Baku', languages: ['Azerbaijani'], population: 9730500, flag: 'https://restcountries.eu/data/aze.svg', currency: 'Azerbaijani manat', }, { name: 'Bahamas', capital: 'Nassau', languages: ['English'], population: 378040, flag: 'https://restcountries.eu/data/bhs.svg', currency: 'Bahamian dollar', }, { name: 'Bahrain', capital: 'Manama', languages: ['Arabic'], population: 1404900, flag: 'https://restcountries.eu/data/bhr.svg', currency: 'Bahraini dinar', }, { name: 'Bangladesh', capital: 'Dhaka', languages: ['Bengali'], population: 161006790, flag: 'https://restcountries.eu/data/bgd.svg', currency: 'Bangladeshi taka', }, { name: 'Barbados', capital: 'Bridgetown', languages: ['English'], population: 285000, flag: 'https://restcountries.eu/data/brb.svg', currency: 'Barbadian dollar', }, { name: 'Belarus', capital: 'Minsk', languages: ['Belarusian', 'Russian'], population: 9498700, flag: 'https://restcountries.eu/data/blr.svg', currency: 'New Belarusian ruble', }, { name: 'Belgium', capital: 'Brussels', languages: ['Dutch', 'French', 'German'], population: 11319511, flag: 'https://restcountries.eu/data/bel.svg', currency: 'Euro', }, { name: 'Belize', capital: 'Belmopan', languages: ['English', 'Spanish'], population: 370300, flag: 'https://restcountries.eu/data/blz.svg', currency: 'Belize dollar', }, { name: 'Benin', capital: 'Porto-Novo', languages: ['French'], population: 10653654, flag: 'https://restcountries.eu/data/ben.svg', currency: 'West African CFA franc', }, { name: 'Bermuda', capital: 'Hamilton', languages: ['English'], population: 61954, flag: 'https://restcountries.eu/data/bmu.svg', currency: 'Bermudian dollar', }, { name: 'Bhutan', capital: 'Thimphu', languages: ['Dzongkha'], population: 775620, flag: 'https://restcountries.eu/data/btn.svg', currency: 'Bhutanese ngultrum', }, { name: 'Bolivia (Plurinational State of)', capital: 'Sucre', languages: ['Spanish', 'Aymara', 'Quechua'], population: 10985059, flag: 'https://restcountries.eu/data/bol.svg', currency: 'Bolivian boliviano', }, { name: 'Bonaire, Sint Eustatius and Saba', capital: 'Kralendijk', languages: ['Dutch'], population: 17408, flag: 'https://restcountries.eu/data/bes.svg', currency: 'United States dollar', }, { name: 'Bosnia and Herzegovina', capital: 'Sarajevo', languages: ['Bosnian', 'Croatian', 'Serbian'], population: 3531159, flag: 'https://restcountries.eu/data/bih.svg', currency: 'Bosnia and Herzegovina convertible mark', }, { name: 'Botswana', capital: 'Gaborone', languages: ['English', 'Tswana'], population: 2141206, flag: 'https://restcountries.eu/data/bwa.svg', currency: 'Botswana pula', }, { name: 'Bouvet Island', capital: '', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 0, flag: 'https://restcountries.eu/data/bvt.svg', currency: 'Norwegian krone', }, { name: 'Brazil', capital: 'Brasília', languages: ['Portuguese'], population: 206135893, flag: 'https://restcountries.eu/data/bra.svg', currency: 'Brazilian real', }, { name: 'British Indian Ocean Territory', capital: 'Diego Garcia', languages: ['English'], population: 3000, flag: 'https://restcountries.eu/data/iot.svg', currency: 'United States dollar', }, { name: 'United States Minor Outlying Islands', capital: '', languages: ['English'], population: 300, flag: 'https://restcountries.eu/data/umi.svg', currency: 'United States Dollar', }, { name: 'Virgin Islands (British)', capital: 'Road Town', languages: ['English'], population: 28514, flag: 'https://restcountries.eu/data/vgb.svg', currency: '[D]', }, { name: 'Virgin Islands (U.S.)', capital: 'Charlotte Amalie', languages: ['English'], population: 114743, flag: 'https://restcountries.eu/data/vir.svg', currency: 'United States dollar', }, { name: 'Brunei Darussalam', capital: 'Bandar Seri Begawan', languages: ['Malay'], population: 411900, flag: 'https://restcountries.eu/data/brn.svg', currency: 'Brunei dollar', }, { name: 'Bulgaria', capital: 'Sofia', languages: ['Bulgarian'], population: 7153784, flag: 'https://restcountries.eu/data/bgr.svg', currency: 'Bulgarian lev', }, { name: 'Burkina Faso', capital: 'Ouagadougou', languages: ['French', 'Fula'], population: 19034397, flag: 'https://restcountries.eu/data/bfa.svg', currency: 'West African CFA franc', }, { name: 'Burundi', capital: 'Bujumbura', languages: ['French', 'Kirundi'], population: 10114505, flag: 'https://restcountries.eu/data/bdi.svg', currency: 'Burundian franc', }, { name: 'Cambodia', capital: 'Phnom Penh', languages: ['Khmer'], population: 15626444, flag: 'https://restcountries.eu/data/khm.svg', currency: 'Cambodian riel', }, { name: 'Cameroon', capital: 'Yaoundé', languages: ['English', 'French'], population: 22709892, flag: 'https://restcountries.eu/data/cmr.svg', currency: 'Central African CFA franc', }, { name: 'Canada', capital: 'Ottawa', languages: ['English', 'French'], population: 36155487, flag: 'https://restcountries.eu/data/can.svg', currency: 'Canadian dollar', }, { name: 'Cabo Verde', capital: 'Praia', languages: ['Portuguese'], population: 531239, flag: 'https://restcountries.eu/data/cpv.svg', currency: 'Cape Verdean escudo', }, { name: 'Cayman Islands', capital: 'George Town', languages: ['English'], population: 58238, flag: 'https://restcountries.eu/data/cym.svg', currency: 'Cayman Islands dollar', }, { name: 'Central African Republic', capital: 'Bangui', languages: ['French', 'Sango'], population: 4998000, flag: 'https://restcountries.eu/data/caf.svg', currency: 'Central African CFA franc', }, { name: 'Chad', capital: "N'Djamena", languages: ['French', 'Arabic'], population: 14497000, flag: 'https://restcountries.eu/data/tcd.svg', currency: 'Central African CFA franc', }, { name: 'Chile', capital: 'Santiago', languages: ['Spanish'], population: 18191900, flag: 'https://restcountries.eu/data/chl.svg', currency: 'Chilean peso', }, { name: 'China', capital: 'Beijing', languages: ['Chinese'], population: 1377422166, flag: 'https://restcountries.eu/data/chn.svg', currency: 'Chinese yuan', }, { name: 'Christmas Island', capital: 'Flying Fish Cove', languages: ['English'], population: 2072, flag: 'https://restcountries.eu/data/cxr.svg', currency: 'Australian dollar', }, { name: 'Cocos (Keeling) Islands', capital: 'West Island', languages: ['English'], population: 550, flag: 'https://restcountries.eu/data/cck.svg', currency: 'Australian dollar', }, { name: 'Colombia', capital: 'Bogotá', languages: ['Spanish'], population: 48759958, flag: 'https://restcountries.eu/data/col.svg', currency: 'Colombian peso', }, { name: 'Comoros', capital: 'Moroni', languages: ['Arabic', 'French'], population: 806153, flag: 'https://restcountries.eu/data/com.svg', currency: 'Comorian franc', }, { name: 'Congo', capital: 'Brazzaville', languages: ['French', 'Lingala'], population: 4741000, flag: 'https://restcountries.eu/data/cog.svg', currency: 'Central African CFA franc', }, { name: 'Congo (Democratic Republic of the)', capital: 'Kinshasa', languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], population: 85026000, flag: 'https://restcountries.eu/data/cod.svg', currency: 'Congolese franc', }, { name: 'Cook Islands', capital: 'Avarua', languages: ['English'], population: 18100, flag: 'https://restcountries.eu/data/cok.svg', currency: 'New Zealand dollar', }, { name: 'Costa Rica', capital: 'San José', languages: ['Spanish'], population: 4890379, flag: 'https://restcountries.eu/data/cri.svg', currency: 'Costa Rican colón', }, { name: 'Croatia', capital: 'Zagreb', languages: ['Croatian'], population: 4190669, flag: 'https://restcountries.eu/data/hrv.svg', currency: 'Croatian kuna', }, { name: 'Cuba', capital: 'Havana', languages: ['Spanish'], population: 11239004, flag: 'https://restcountries.eu/data/cub.svg', currency: 'Cuban convertible peso', }, { name: 'Curaçao', capital: 'Willemstad', languages: ['Dutch', '(Eastern) Punjabi', 'English'], population: 154843, flag: 'https://restcountries.eu/data/cuw.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Cyprus', capital: 'Nicosia', languages: ['Greek (modern)', 'Turkish', 'Armenian'], population: 847000, flag: 'https://restcountries.eu/data/cyp.svg', currency: 'Euro', }, { name: 'Czech Republic', capital: 'Prague', languages: ['Czech', 'Slovak'], population: 10558524, flag: 'https://restcountries.eu/data/cze.svg', currency: 'Czech koruna', }, { name: 'Denmark', capital: 'Copenhagen', languages: ['Danish'], population: 5717014, flag: 'https://restcountries.eu/data/dnk.svg', currency: 'Danish krone', }, { name: 'Djibouti', capital: 'Djibouti', languages: ['French', 'Arabic'], population: 900000, flag: 'https://restcountries.eu/data/dji.svg', currency: 'Djiboutian franc', }, { name: 'Dominica', capital: 'Roseau', languages: ['English'], population: 71293, flag: 'https://restcountries.eu/data/dma.svg', currency: 'East Caribbean dollar', }, { name: 'Dominican Republic', capital: 'Santo Domingo', languages: ['Spanish'], population: 10075045, flag: 'https://restcountries.eu/data/dom.svg', currency: 'Dominican peso', }, { name: 'Ecuador', capital: 'Quito', languages: ['Spanish'], population: 16545799, flag: 'https://restcountries.eu/data/ecu.svg', currency: 'United States dollar', }, { name: 'Egypt', capital: 'Cairo', languages: ['Arabic'], population: 91290000, flag: 'https://restcountries.eu/data/egy.svg', currency: 'Egyptian pound', }, { name: 'El Salvador', capital: 'San Salvador', languages: ['Spanish'], population: 6520675, flag: 'https://restcountries.eu/data/slv.svg', currency: 'United States dollar', }, { name: 'Equatorial Guinea', capital: 'Malabo', languages: ['Spanish', 'French'], population: 1222442, flag: 'https://restcountries.eu/data/gnq.svg', currency: 'Central African CFA franc', }, { name: 'Eritrea', capital: 'Asmara', languages: ['Tigrinya', 'Arabic', 'English'], population: 5352000, flag: 'https://restcountries.eu/data/eri.svg', currency: 'Eritrean nakfa', }, { name: 'Estonia', capital: 'Tallinn', languages: ['Estonian'], population: 1315944, flag: 'https://restcountries.eu/data/est.svg', currency: 'Euro', }, { name: 'Ethiopia', capital: 'Addis Ababa', languages: ['Amharic'], population: 92206005, flag: 'https://restcountries.eu/data/eth.svg', currency: 'Ethiopian birr', }, { name: 'Falkland Islands (Malvinas)', capital: 'Stanley', languages: ['English'], population: 2563, flag: 'https://restcountries.eu/data/flk.svg', currency: 'Falkland Islands pound', }, { name: 'Faroe Islands', capital: 'Tórshavn', languages: ['Faroese'], population: 49376, flag: 'https://restcountries.eu/data/fro.svg', currency: 'Danish krone', }, { name: 'Fiji', capital: 'Suva', languages: ['English', 'Fijian', 'Hindi', 'Urdu'], population: 867000, flag: 'https://restcountries.eu/data/fji.svg', currency: 'Fijian dollar', }, { name: 'Finland', capital: 'Helsinki', languages: ['Finnish', 'Swedish'], population: 5491817, flag: 'https://restcountries.eu/data/fin.svg', currency: 'Euro', }, { name: 'France', capital: 'Paris', languages: ['French'], population: 66710000, flag: 'https://restcountries.eu/data/fra.svg', currency: 'Euro', }, { name: 'French Guiana', capital: 'Cayenne', languages: ['French'], population: 254541, flag: 'https://restcountries.eu/data/guf.svg', currency: 'Euro', }, { name: 'French Polynesia', capital: 'Papeetē', languages: ['French'], population: 271800, flag: 'https://restcountries.eu/data/pyf.svg', currency: 'CFP franc', }, { name: 'French Southern Territories', capital: 'Port-aux-Français', languages: ['French'], population: 140, flag: 'https://restcountries.eu/data/atf.svg', currency: 'Euro', }, { name: 'Gabon', capital: 'Libreville', languages: ['French'], population: 1802278, flag: 'https://restcountries.eu/data/gab.svg', currency: 'Central African CFA franc', }, { name: 'Gambia', capital: 'Banjul', languages: ['English'], population: 1882450, flag: 'https://restcountries.eu/data/gmb.svg', currency: 'Gambian dalasi', }, { name: 'Georgia', capital: 'Tbilisi', languages: ['Georgian'], population: 3720400, flag: 'https://restcountries.eu/data/geo.svg', currency: 'Georgian Lari', }, { name: 'Germany', capital: 'Berlin', languages: ['German'], population: 81770900, flag: 'https://restcountries.eu/data/deu.svg', currency: 'Euro', }, { name: 'Ghana', capital: 'Accra', languages: ['English'], population: 27670174, flag: 'https://restcountries.eu/data/gha.svg', currency: 'Ghanaian cedi', }, { name: 'Gibraltar', capital: 'Gibraltar', languages: ['English'], population: 33140, flag: 'https://restcountries.eu/data/gib.svg', currency: 'Gibraltar pound', }, { name: 'Greece', capital: 'Athens', languages: ['Greek (modern)'], population: 10858018, flag: 'https://restcountries.eu/data/grc.svg', currency: 'Euro', }, { name: 'Greenland', capital: 'Nuuk', languages: ['Kalaallisut'], population: 55847, flag: 'https://restcountries.eu/data/grl.svg', currency: 'Danish krone', }, { name: 'Grenada', capital: "St. George's", languages: ['English'], population: 103328, flag: 'https://restcountries.eu/data/grd.svg', currency: 'East Caribbean dollar', }, { name: 'Guadeloupe', capital: 'Basse-Terre', languages: ['French'], population: 400132, flag: 'https://restcountries.eu/data/glp.svg', currency: 'Euro', }, { name: 'Guam', capital: 'Hagåtña', languages: ['English', 'Chamorro', 'Spanish'], population: 184200, flag: 'https://restcountries.eu/data/gum.svg', currency: 'United States dollar', }, { name: 'Guatemala', capital: 'Guatemala City', languages: ['Spanish'], population: 16176133, flag: 'https://restcountries.eu/data/gtm.svg', currency: 'Guatemalan quetzal', }, { name: 'Guernsey', capital: 'St. Peter Port', languages: ['English', 'French'], population: 62999, flag: 'https://restcountries.eu/data/ggy.svg', currency: 'British pound', }, { name: 'Guinea', capital: 'Conakry', languages: ['French', 'Fula'], population: 12947000, flag: 'https://restcountries.eu/data/gin.svg', currency: 'Guinean franc', }, { name: 'Guinea-Bissau', capital: 'Bissau', languages: ['Portuguese'], population: 1547777, flag: 'https://restcountries.eu/data/gnb.svg', currency: 'West African CFA franc', }, { name: 'Guyana', capital: 'Georgetown', languages: ['English'], population: 746900, flag: 'https://restcountries.eu/data/guy.svg', currency: 'Guyanese dollar', }, { name: 'Haiti', capital: 'Port-au-Prince', languages: ['French', 'Haitian'], population: 11078033, flag: 'https://restcountries.eu/data/hti.svg', currency: 'Haitian gourde', }, { name: 'Heard Island and McDonald Islands', capital: '', languages: ['English'], population: 0, flag: 'https://restcountries.eu/data/hmd.svg', currency: 'Australian dollar', }, { name: 'Holy See', capital: 'Rome', languages: ['Latin', 'Italian', 'French', 'German'], population: 451, flag: 'https://restcountries.eu/data/vat.svg', currency: 'Euro', }, { name: 'Honduras', capital: 'Tegucigalpa', languages: ['Spanish'], population: 8576532, flag: 'https://restcountries.eu/data/hnd.svg', currency: 'Honduran lempira', }, { name: 'Hong Kong', capital: 'City of Victoria', languages: ['English', 'Chinese'], population: 7324300, flag: 'https://restcountries.eu/data/hkg.svg', currency: 'Hong Kong dollar', }, { name: 'Hungary', capital: 'Budapest', languages: ['Hungarian'], population: 9823000, flag: 'https://restcountries.eu/data/hun.svg', currency: 'Hungarian forint', }, { name: 'Iceland', capital: 'Reykjavík', languages: ['Icelandic'], population: 334300, flag: 'https://restcountries.eu/data/isl.svg', currency: 'Icelandic króna', }, { name: 'India', capital: 'New Delhi', languages: ['Hindi', 'English'], population: 1295210000, flag: 'https://restcountries.eu/data/ind.svg', currency: 'Indian rupee', }, { name: 'Indonesia', capital: 'Jakarta', languages: ['Indonesian'], population: 258705000, flag: 'https://restcountries.eu/data/idn.svg', currency: 'Indonesian rupiah', }, { name: "Côte d'Ivoire", capital: 'Yamoussoukro', languages: ['French'], population: 22671331, flag: 'https://restcountries.eu/data/civ.svg', currency: 'West African CFA franc', }, { name: 'Iran (Islamic Republic of)', capital: 'Tehran', languages: ['Persian (Farsi)'], population: 79369900, flag: 'https://restcountries.eu/data/irn.svg', currency: 'Iranian rial', }, { name: 'Iraq', capital: 'Baghdad', languages: ['Arabic', 'Kurdish'], population: 37883543, flag: 'https://restcountries.eu/data/irq.svg', currency: 'Iraqi dinar', }, { name: 'Ireland', capital: 'Dublin', languages: ['Irish', 'English'], population: 6378000, flag: 'https://restcountries.eu/data/irl.svg', currency: 'Euro', }, { name: 'Isle of Man', capital: 'Douglas', languages: ['English', 'Manx'], population: 84497, flag: 'https://restcountries.eu/data/imn.svg', currency: 'British pound', }, { name: 'Israel', capital: 'Jerusalem', languages: ['Hebrew (modern)', 'Arabic'], population: 8527400, flag: 'https://restcountries.eu/data/isr.svg', currency: 'Israeli new shekel', }, { name: 'Italy', capital: 'Rome', languages: ['Italian'], population: 60665551, flag: 'https://restcountries.eu/data/ita.svg', currency: 'Euro', }, { name: 'Jamaica', capital: 'Kingston', languages: ['English'], population: 2723246, flag: 'https://restcountries.eu/data/jam.svg', currency: 'Jamaican dollar', }, { name: 'Japan', capital: 'Tokyo', languages: ['Japanese'], population: 126960000, flag: 'https://restcountries.eu/data/jpn.svg', currency: 'Japanese yen', }, { name: 'Jersey', capital: 'Saint Helier', languages: ['English', 'French'], population: 100800, flag: 'https://restcountries.eu/data/jey.svg', currency: 'British pound', }, { name: 'Jordan', capital: 'Amman', languages: ['Arabic'], population: 9531712, flag: 'https://restcountries.eu/data/jor.svg', currency: 'Jordanian dinar', }, { name: 'Kazakhstan', capital: 'Astana', languages: ['Kazakh', 'Russian'], population: 17753200, flag: 'https://restcountries.eu/data/kaz.svg', currency: 'Kazakhstani tenge', }, { name: 'Kenya', capital: 'Nairobi', languages: ['English', 'Swahili'], population: 47251000, flag: 'https://restcountries.eu/data/ken.svg', currency: 'Kenyan shilling', }, { name: 'Kiribati', capital: 'South Tarawa', languages: ['English'], population: 113400, flag: 'https://restcountries.eu/data/kir.svg', currency: 'Australian dollar', }, { name: 'Kuwait', capital: 'Kuwait City', languages: ['Arabic'], population: 4183658, flag: 'https://restcountries.eu/data/kwt.svg', currency: 'Kuwaiti dinar', }, { name: 'Kyrgyzstan', capital: 'Bishkek', languages: ['Kyrgyz', 'Russian'], population: 6047800, flag: 'https://restcountries.eu/data/kgz.svg', currency: 'Kyrgyzstani som', }, { name: "Lao People's Democratic Republic", capital: 'Vientiane', languages: ['Lao'], population: 6492400, flag: 'https://restcountries.eu/data/lao.svg', currency: 'Lao kip', }, { name: 'Latvia', capital: 'Riga', languages: ['Latvian'], population: 1961600, flag: 'https://restcountries.eu/data/lva.svg', currency: 'Euro', }, { name: 'Lebanon', capital: 'Beirut', languages: ['Arabic', 'French'], population: 5988000, flag: 'https://restcountries.eu/data/lbn.svg', currency: 'Lebanese pound', }, { name: 'Lesotho', capital: 'Maseru', languages: ['English', 'Southern Sotho'], population: 1894194, flag: 'https://restcountries.eu/data/lso.svg', currency: 'Lesotho loti', }, { name: 'Liberia', capital: 'Monrovia', languages: ['English'], population: 4615000, flag: 'https://restcountries.eu/data/lbr.svg', currency: 'Liberian dollar', }, { name: 'Libya', capital: 'Tripoli', languages: ['Arabic'], population: 6385000, flag: 'https://restcountries.eu/data/lby.svg', currency: 'Libyan dinar', }, { name: 'Liechtenstein', capital: 'Vaduz', languages: ['German'], population: 37623, flag: 'https://restcountries.eu/data/lie.svg', currency: 'Swiss franc', }, { name: 'Lithuania', capital: 'Vilnius', languages: ['Lithuanian'], population: 2872294, flag: 'https://restcountries.eu/data/ltu.svg', currency: 'Euro', }, { name: 'Luxembourg', capital: 'Luxembourg', languages: ['French', 'German', 'Luxembourgish'], population: 576200, flag: 'https://restcountries.eu/data/lux.svg', currency: 'Euro', }, { name: 'Macao', capital: '', languages: ['Chinese', 'Portuguese'], population: 649100, flag: 'https://restcountries.eu/data/mac.svg', currency: 'Macanese pataca', }, { name: 'Macedonia (the former Yugoslav Republic of)', capital: 'Skopje', languages: ['Macedonian'], population: 2058539, flag: 'https://restcountries.eu/data/mkd.svg', currency: 'Macedonian denar', }, { name: 'Madagascar', capital: 'Antananarivo', languages: ['French', 'Malagasy'], population: 22434363, flag: 'https://restcountries.eu/data/mdg.svg', currency: 'Malagasy ariary', }, { name: 'Malawi', capital: 'Lilongwe', languages: ['English', 'Chichewa'], population: 16832910, flag: 'https://restcountries.eu/data/mwi.svg', currency: 'Malawian kwacha', }, { name: 'Malaysia', capital: 'Kuala Lumpur', languages: ['Malaysian'], population: 31405416, flag: 'https://restcountries.eu/data/mys.svg', currency: 'Malaysian ringgit', }, { name: 'Maldives', capital: 'Malé', languages: ['Divehi'], population: 344023, flag: 'https://restcountries.eu/data/mdv.svg', currency: 'Maldivian rufiyaa', }, { name: 'Mali', capital: 'Bamako', languages: ['French'], population: 18135000, flag: 'https://restcountries.eu/data/mli.svg', currency: 'West African CFA franc', }, { name: 'Malta', capital: 'Valletta', languages: ['Maltese', 'English'], population: 425384, flag: 'https://restcountries.eu/data/mlt.svg', currency: 'Euro', }, { name: 'Marshall Islands', capital: 'Majuro', languages: ['English', 'Marshallese'], population: 54880, flag: 'https://restcountries.eu/data/mhl.svg', currency: 'United States dollar', }, { name: 'Martinique', capital: 'Fort-de-France', languages: ['French'], population: 378243, flag: 'https://restcountries.eu/data/mtq.svg', currency: 'Euro', }, { name: 'Mauritania', capital: 'Nouakchott', languages: ['Arabic'], population: 3718678, flag: 'https://restcountries.eu/data/mrt.svg', currency: 'Mauritanian ouguiya', }, { name: 'Mauritius', capital: 'Port Louis', languages: ['English'], population: 1262879, flag: 'https://restcountries.eu/data/mus.svg', currency: 'Mauritian rupee', }, { name: 'Mayotte', capital: 'Mamoudzou', languages: ['French'], population: 226915, flag: 'https://restcountries.eu/data/myt.svg', currency: 'Euro', }, { name: 'Mexico', capital: 'Mexico City', languages: ['Spanish'], population: 122273473, flag: 'https://restcountries.eu/data/mex.svg', currency: 'Mexican peso', }, { name: 'Micronesia (Federated States of)', capital: 'Palikir', languages: ['English'], population: 102800, flag: 'https://restcountries.eu/data/fsm.svg', currency: '[D]', }, { name: 'Moldova (Republic of)', capital: 'Chișinău', languages: ['Romanian'], population: 3553100, flag: 'https://restcountries.eu/data/mda.svg', currency: 'Moldovan leu', }, { name: 'Monaco', capital: 'Monaco', languages: ['French'], population: 38400, flag: 'https://restcountries.eu/data/mco.svg', currency: 'Euro', }, { name: 'Mongolia', capital: 'Ulan Bator', languages: ['Mongolian'], population: 3093100, flag: 'https://restcountries.eu/data/mng.svg', currency: 'Mongolian tögrög', }, { name: 'Montenegro', capital: 'Podgorica', languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], population: 621810, flag: 'https://restcountries.eu/data/mne.svg', currency: 'Euro', }, { name: 'Montserrat', capital: 'Plymouth', languages: ['English'], population: 4922, flag: 'https://restcountries.eu/data/msr.svg', currency: 'East Caribbean dollar', }, { name: 'Morocco', capital: 'Rabat', languages: ['Arabic'], population: 33337529, flag: 'https://restcountries.eu/data/mar.svg', currency: 'Moroccan dirham', }, { name: 'Mozambique', capital: 'Maputo', languages: ['Portuguese'], population: 26423700, flag: 'https://restcountries.eu/data/moz.svg', currency: 'Mozambican metical', }, { name: 'Myanmar', capital: 'Naypyidaw', languages: ['Burmese'], population: 51419420, flag: 'https://restcountries.eu/data/mmr.svg', currency: 'Burmese kyat', }, { name: 'Namibia', capital: 'Windhoek', languages: ['English', 'Afrikaans'], population: 2324388, flag: 'https://restcountries.eu/data/nam.svg', currency: 'Namibian dollar', }, { name: 'Nauru', capital: 'Yaren', languages: ['English', 'Nauruan'], population: 10084, flag: 'https://restcountries.eu/data/nru.svg', currency: 'Australian dollar', }, { name: 'Nepal', capital: 'Kathmandu', languages: ['Nepali'], population: 28431500, flag: 'https://restcountries.eu/data/npl.svg', currency: 'Nepalese rupee', }, { name: 'Netherlands', capital: 'Amsterdam', languages: ['Dutch'], population: 17019800, flag: 'https://restcountries.eu/data/nld.svg', currency: 'Euro', }, { name: 'New Caledonia', capital: 'Nouméa', languages: ['French'], population: 268767, flag: 'https://restcountries.eu/data/ncl.svg', currency: 'CFP franc', }, { name: 'New Zealand', capital: 'Wellington', languages: ['English', 'Māori'], population: 4697854, flag: 'https://restcountries.eu/data/nzl.svg', currency: 'New Zealand dollar', }, { name: 'Nicaragua', capital: 'Managua', languages: ['Spanish'], population: 6262703, flag: 'https://restcountries.eu/data/nic.svg', currency: 'Nicaraguan córdoba', }, { name: 'Niger', capital: 'Niamey', languages: ['French'], population: 20715000, flag: 'https://restcountries.eu/data/ner.svg', currency: 'West African CFA franc', }, { name: 'Nigeria', capital: 'Abuja', languages: ['English'], population: 186988000, flag: 'https://restcountries.eu/data/nga.svg', currency: 'Nigerian naira', }, { name: 'Niue', capital: 'Alofi', languages: ['English'], population: 1470, flag: 'https://restcountries.eu/data/niu.svg', currency: 'New Zealand dollar', }, { name: 'Norfolk Island', capital: 'Kingston', languages: ['English'], population: 2302, flag: 'https://restcountries.eu/data/nfk.svg', currency: 'Australian dollar', }, { name: "Korea (Democratic People's Republic of)", capital: 'Pyongyang', languages: ['Korean'], population: 25281000, flag: 'https://restcountries.eu/data/prk.svg', currency: 'North Korean won', }, { name: 'Northern Mariana Islands', capital: 'Saipan', languages: ['English', 'Chamorro'], population: 56940, flag: 'https://restcountries.eu/data/mnp.svg', currency: 'United States dollar', }, { name: 'Norway', capital: 'Oslo', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 5223256, flag: 'https://restcountries.eu/data/nor.svg', currency: 'Norwegian krone', }, { name: 'Oman', capital: 'Muscat', languages: ['Arabic'], population: 4420133, flag: 'https://restcountries.eu/data/omn.svg', currency: 'Omani rial', }, { name: 'Pakistan', capital: 'Islamabad', languages: ['English', 'Urdu'], population: 194125062, flag: 'https://restcountries.eu/data/pak.svg', currency: 'Pakistani rupee', }, { name: 'Palau', capital: 'Ngerulmud', languages: ['English'], population: 17950, flag: 'https://restcountries.eu/data/plw.svg', currency: '[E]', }, { name: 'Palestine, State of', capital: 'Ramallah', languages: ['Arabic'], population: 4682467, flag: 'https://restcountries.eu/data/pse.svg', currency: 'Israeli new sheqel', }, { name: 'Panama', capital: 'Panama City', languages: ['Spanish'], population: 3814672, flag: 'https://restcountries.eu/data/pan.svg', currency: 'Panamanian balboa', }, { name: 'Papua New Guinea', capital: 'Port Moresby', languages: ['English'], population: 8083700, flag: 'https://restcountries.eu/data/png.svg', currency: 'Papua New Guinean kina', }, { name: 'Paraguay', capital: 'Asunción', languages: ['Spanish', 'Guaraní'], population: 6854536, flag: 'https://restcountries.eu/data/pry.svg', currency: 'Paraguayan guaraní', }, { name: 'Peru', capital: 'Lima', languages: ['Spanish'], population: 31488700, flag: 'https://restcountries.eu/data/per.svg', currency: 'Peruvian sol', }, { name: 'Philippines', capital: 'Manila', languages: ['English'], population: 103279800, flag: 'https://restcountries.eu/data/phl.svg', currency: 'Philippine peso', }, { name: 'Pitcairn', capital: 'Adamstown', languages: ['English'], population: 56, flag: 'https://restcountries.eu/data/pcn.svg', currency: 'New Zealand dollar', }, { name: 'Poland', capital: 'Warsaw', languages: ['Polish'], population: 38437239, flag: 'https://restcountries.eu/data/pol.svg', currency: 'Polish złoty', }, { name: 'Portugal', capital: 'Lisbon', languages: ['Portuguese'], population: 10374822, flag: 'https://restcountries.eu/data/prt.svg', currency: 'Euro', }, { name: 'Puerto Rico', capital: 'San Juan', languages: ['Spanish', 'English'], population: 3474182, flag: 'https://restcountries.eu/data/pri.svg', currency: 'United States dollar', }, { name: 'Qatar', capital: 'Doha', languages: ['Arabic'], population: 2587564, flag: 'https://restcountries.eu/data/qat.svg', currency: 'Qatari riyal', }, { name: 'Republic of Kosovo', capital: 'Pristina', languages: ['Albanian', 'Serbian'], population: 1733842, flag: 'https://restcountries.eu/data/kos.svg', currency: 'Euro', }, { name: 'Réunion', capital: 'Saint-Denis', languages: ['French'], population: 840974, flag: 'https://restcountries.eu/data/reu.svg', currency: 'Euro', }, { name: 'Romania', capital: 'Bucharest', languages: ['Romanian'], population: 19861408, flag: 'https://restcountries.eu/data/rou.svg', currency: 'Romanian leu', }, { name: 'Russian Federation', capital: 'Moscow', languages: ['Russian'], population: 146599183, flag: 'https://restcountries.eu/data/rus.svg', currency: 'Russian ruble', }, { name: 'Rwanda', capital: 'Kigali', languages: ['Kinyarwanda', 'English', 'French'], population: 11553188, flag: 'https://restcountries.eu/data/rwa.svg', currency: 'Rwandan franc', }, { name: 'Saint Barthélemy', capital: 'Gustavia', languages: ['French'], population: 9417, flag: 'https://restcountries.eu/data/blm.svg', currency: 'Euro', }, { name: 'Saint Helena, Ascension and Tristan da Cunha', capital: 'Jamestown', languages: ['English'], population: 4255, flag: 'https://restcountries.eu/data/shn.svg', currency: 'Saint Helena pound', }, { name: 'Saint Kitts and Nevis', capital: 'Basseterre', languages: ['English'], population: 46204, flag: 'https://restcountries.eu/data/kna.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Lucia', capital: 'Castries', languages: ['English'], population: 186000, flag: 'https://restcountries.eu/data/lca.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Martin (French part)', capital: 'Marigot', languages: ['English', 'French', 'Dutch'], population: 36979, flag: 'https://restcountries.eu/data/maf.svg', currency: 'Euro', }, { name: 'Saint Pierre and Miquelon', capital: 'Saint-Pierre', languages: ['French'], population: 6069, flag: 'https://restcountries.eu/data/spm.svg', currency: 'Euro', }, { name: 'Saint Vincent and the Grenadines', capital: 'Kingstown', languages: ['English'], population: 109991, flag: 'https://restcountries.eu/data/vct.svg', currency: 'East Caribbean dollar', }, { name: 'Samoa', capital: 'Apia', languages: ['Samoan', 'English'], population: 194899, flag: 'https://restcountries.eu/data/wsm.svg', currency: 'Samoan tālā', }, { name: 'San Marino', capital: 'City of San Marino', languages: ['Italian'], population: 33005, flag: 'https://restcountries.eu/data/smr.svg', currency: 'Euro', }, { name: 'Sao Tome and Principe', capital: 'São Tomé', languages: ['Portuguese'], population: 187356, flag: 'https://restcountries.eu/data/stp.svg', currency: 'São Tomé and Príncipe dobra', }, { name: 'Saudi Arabia', capital: 'Riyadh', languages: ['Arabic'], population: 32248200, flag: 'https://restcountries.eu/data/sau.svg', currency: 'Saudi riyal', }, { name: 'Senegal', capital: 'Dakar', languages: ['French'], population: 14799859, flag: 'https://restcountries.eu/data/sen.svg', currency: 'West African CFA franc', }, { name: 'Serbia', capital: 'Belgrade', languages: ['Serbian'], population: 7076372, flag: 'https://restcountries.eu/data/srb.svg', currency: 'Serbian dinar', }, { name: 'Seychelles', capital: 'Victoria', languages: ['French', 'English'], population: 91400, flag: 'https://restcountries.eu/data/syc.svg', currency: 'Seychellois rupee', }, { name: 'Sierra Leone', capital: 'Freetown', languages: ['English'], population: 7075641, flag: 'https://restcountries.eu/data/sle.svg', currency: 'Sierra Leonean leone', }, { name: 'Singapore', capital: 'Singapore', languages: ['English', 'Malay', 'Tamil', 'Chinese'], population: 5535000, flag: 'https://restcountries.eu/data/sgp.svg', currency: 'Brunei dollar', }, { name: 'Sint Maarten (Dutch part)', capital: 'Philipsburg', languages: ['Dutch', 'English'], population: 38247, flag: 'https://restcountries.eu/data/sxm.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Slovakia', capital: 'Bratislava', languages: ['Slovak'], population: 5426252, flag: 'https://restcountries.eu/data/svk.svg', currency: 'Euro', }, { name: 'Slovenia', capital: 'Ljubljana', languages: ['Slovene'], population: 2064188, flag: 'https://restcountries.eu/data/svn.svg', currency: 'Euro', }, { name: 'Solomon Islands', capital: 'Honiara', languages: ['English'], population: 642000, flag: 'https://restcountries.eu/data/slb.svg', currency: 'Solomon Islands dollar', }, { name: 'Somalia', capital: 'Mogadishu', languages: ['Somali', 'Arabic'], population: 11079000, flag: 'https://restcountries.eu/data/som.svg', currency: 'Somali shilling', }, { name: 'South Africa', capital: 'Pretoria', languages: [ 'Afrikaans', 'English', 'Southern Ndebele', 'Southern Sotho', 'Swati', 'Tswana', 'Tsonga', 'Venda', 'Xhosa', 'Zulu', ], population: 55653654, flag: 'https://restcountries.eu/data/zaf.svg', currency: 'South African rand', }, { name: 'South Georgia and the South Sandwich Islands', capital: 'King Edward Point', languages: ['English'], population: 30, flag: 'https://restcountries.eu/data/sgs.svg', currency: 'British pound', }, { name: 'Korea (Republic of)', capital: 'Seoul', languages: ['Korean'], population: 50801405, flag: 'https://restcountries.eu/data/kor.svg', currency: 'South Korean won', }, { name: 'South Sudan', capital: 'Juba', languages: ['English'], population: 12131000, flag: 'https://restcountries.eu/data/ssd.svg', currency: 'South Sudanese pound', }, { name: 'Spain', capital: 'Madrid', languages: ['Spanish'], population: 46438422, flag: 'https://restcountries.eu/data/esp.svg', currency: 'Euro', }, { name: 'Sri Lanka', capital: 'Colombo', languages: ['Sinhalese', 'Tamil'], population: 20966000, flag: 'https://restcountries.eu/data/lka.svg', currency: 'Sri Lankan rupee', }, { name: 'Sudan', capital: 'Khartoum', languages: ['Arabic', 'English'], population: 39598700, flag: 'https://restcountries.eu/data/sdn.svg', currency: 'Sudanese pound', }, { name: 'Suriname', capital: 'Paramaribo', languages: ['Dutch'], population: 541638, flag: 'https://restcountries.eu/data/sur.svg', currency: 'Surinamese dollar', }, { name: 'Svalbard and Jan Mayen', capital: 'Longyearbyen', languages: ['Norwegian'], population: 2562, flag: 'https://restcountries.eu/data/sjm.svg', currency: 'Norwegian krone', }, { name: 'Swaziland', capital: 'Lobamba', languages: ['English', 'Swati'], population: 1132657, flag: 'https://restcountries.eu/data/swz.svg', currency: 'Swazi lilangeni', }, { name: 'Sweden', capital: 'Stockholm', languages: ['Swedish'], population: 9894888, flag: 'https://restcountries.eu/data/swe.svg', currency: 'Swedish krona', }, { name: 'Switzerland', capital: 'Bern', languages: ['German', 'French', 'Italian'], population: 8341600, flag: 'https://restcountries.eu/data/che.svg', currency: 'Swiss franc', }, { name: 'Syrian Arab Republic', capital: 'Damascus', languages: ['Arabic'], population: 18564000, flag: 'https://restcountries.eu/data/syr.svg', currency: 'Syrian pound', }, { name: 'Taiwan', capital: 'Taipei', languages: ['Chinese'], population: 23503349, flag: 'https://restcountries.eu/data/twn.svg', currency: 'New Taiwan dollar', }, { name: 'Tajikistan', capital: 'Dushanbe', languages: ['Tajik', 'Russian'], population: 8593600, flag: 'https://restcountries.eu/data/tjk.svg', currency: 'Tajikistani somoni', }, { name: 'Tanzania, United Republic of', capital: 'Dodoma', languages: ['Swahili', 'English'], population: 55155000, flag: 'https://restcountries.eu/data/tza.svg', currency: 'Tanzanian shilling', }, { name: 'Thailand', capital: 'Bangkok', languages: ['Thai'], population: 65327652, flag: 'https://restcountries.eu/data/tha.svg', currency: 'Thai baht', }, { name: 'Timor-Leste', capital: 'Dili', languages: ['Portuguese'], population: 1167242, flag: 'https://restcountries.eu/data/tls.svg', currency: 'United States dollar', }, { name: 'Togo', capital: 'Lomé', languages: ['French'], population: 7143000, flag: 'https://restcountries.eu/data/tgo.svg', currency: 'West African CFA franc', }, { name: 'Tokelau', capital: 'Fakaofo', languages: ['English'], population: 1411, flag: 'https://restcountries.eu/data/tkl.svg', currency: 'New Zealand dollar', }, { name: 'Tonga', capital: "Nuku'alofa", languages: ['English', 'Tonga (Tonga Islands)'], population: 103252, flag: 'https://restcountries.eu/data/ton.svg', currency: 'Tongan paʻanga', }, { name: 'Trinidad and Tobago', capital: 'Port of Spain', languages: ['English'], population: 1349667, flag: 'https://restcountries.eu/data/tto.svg', currency: 'Trinidad and Tobago dollar', }, { name: 'Tunisia', capital: 'Tunis', languages: ['Arabic'], population: 11154400, flag: 'https://restcountries.eu/data/tun.svg', currency: 'Tunisian dinar', }, { name: 'Turkey', capital: 'Ankara', languages: ['Turkish'], population: 78741053, flag: 'https://restcountries.eu/data/tur.svg', currency: 'Turkish lira', }, { name: 'Turkmenistan', capital: 'Ashgabat', languages: ['Turkmen', 'Russian'], population: 4751120, flag: 'https://restcountries.eu/data/tkm.svg', currency: 'Turkmenistan manat', }, { name: 'Turks and Caicos Islands', capital: 'Cockburn Town', languages: ['English'], population: 31458, flag: 'https://restcountries.eu/data/tca.svg', currency: 'United States dollar', }, { name: 'Tuvalu', capital: 'Funafuti', languages: ['English'], population: 10640, flag: 'https://restcountries.eu/data/tuv.svg', currency: 'Australian dollar', }, { name: 'Uganda', capital: 'Kampala', languages: ['English', 'Swahili'], population: 33860700, flag: 'https://restcountries.eu/data/uga.svg', currency: 'Ugandan shilling', }, { name: 'Ukraine', capital: 'Kiev', languages: ['Ukrainian'], population: 42692393, flag: 'https://restcountries.eu/data/ukr.svg', currency: 'Ukrainian hryvnia', }, { name: 'United Arab Emirates', capital: 'Abu Dhabi', languages: ['Arabic'], population: 9856000, flag: 'https://restcountries.eu/data/are.svg', currency: 'United Arab Emirates dirham', }, { name: 'United Kingdom of Great Britain and Northern Ireland', capital: 'London', languages: ['English'], population: 65110000, flag: 'https://restcountries.eu/data/gbr.svg', currency: 'British pound', }, { name: 'United States of America', capital: 'Washington, D.C.', languages: ['English'], population: 323947000, flag: 'https://restcountries.eu/data/usa.svg', currency: 'United States dollar', }, { name: 'Uruguay', capital: 'Montevideo', languages: ['Spanish'], population: 3480222, flag: 'https://restcountries.eu/data/ury.svg', currency: 'Uruguayan peso', }, { name: 'Uzbekistan', capital: 'Tashkent', languages: ['Uzbek', 'Russian'], population: 31576400, flag: 'https://restcountries.eu/data/uzb.svg', currency: "Uzbekistani so'm", }, { name: 'Vanuatu', capital: 'Port Vila', languages: ['Bislama', 'English', 'French'], population: 277500, flag: 'https://restcountries.eu/data/vut.svg', currency: 'Vanuatu vatu', }, { name: 'Venezuela (Bolivarian Republic of)', capital: 'Caracas', languages: ['Spanish'], population: 31028700, flag: 'https://restcountries.eu/data/ven.svg', currency: 'Venezuelan bolívar', }, { name: 'Viet Nam', capital: 'Hanoi', languages: ['Vietnamese'], population: 92700000, flag: 'https://restcountries.eu/data/vnm.svg', currency: 'Vietnamese đồng', }, { name: 'Wallis and Futuna', capital: 'Mata-Utu', languages: ['French'], population: 11750, flag: 'https://restcountries.eu/data/wlf.svg', currency: 'CFP franc', }, { name: 'Western Sahara', capital: 'El Aaiún', languages: ['Spanish'], population: 510713, flag: 'https://restcountries.eu/data/esh.svg', currency: 'Moroccan dirham', }, { name: 'Yemen', capital: "Sana'a", languages: ['Arabic'], population: 27478000, flag: 'https://restcountries.eu/data/yem.svg', currency: 'Yemeni rial', }, { name: 'Zambia', capital: 'Lusaka', languages: ['English'], population: 15933883, flag: 'https://restcountries.eu/data/zmb.svg', currency: 'Zambian kwacha', }, { name: 'Zimbabwe', capital: 'Harare', languages: ['English', 'Shona', 'Northern Ndebele'], population: 14240168, flag: 'https://restcountries.eu/data/zwe.svg', currency: 'Botswana pula', }, ]; ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/data/ten_most_highest_populations.js ================================================ export const tenHighestPopulation = [ { country: 'World', population: 7693165599 }, { country: 'China', population: 1377422166 }, { country: 'India', population: 1295210000 }, { country: 'United States of America', population: 323947000 }, { country: 'Indonesia', population: 258705000 }, { country: 'Brazil', population: 206135893 }, { country: 'Pakistan', population: 194125062 }, { country: 'Nigeria', population: 186988000 }, { country: 'Bangladesh', population: 161006790 }, { country: 'Russian Federation', population: 146599183 }, { country: 'Japan', population: 126960000 }, ] ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/index.js ================================================ // index.js import React from 'react' import ReactDOM from 'react-dom' import App from './App' import './styles/index.css' // class based component const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/styles/button-styles.js ================================================ // CSS styles in JavaScript Object export const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: 3, cursor: 'pointer', fontSize: 22, color: 'white', margin: '0 auto', } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/styles/common.css ================================================ * { box-sizing: border-box; padding: 0; margin: 0; } html, body { height: 100%; line-height: 1.5; font-family: 'Roboto'; font-weight: 300; color: black; overflow-x: hidden; font-size: 110%; } #root { min-height: 100%; position: relative; letter-spacing: 1.25px; } .header-wrapper, .main-wrapper, .footer-wrapper { width: 85%; margin: auto; } .header-wrapper, .main-wrapper { padding: 10px; margin: 2px auto; } h1 { font-size: 70px; font-weight: 300; } h2, h3 { font-weight: 300; } main { padding: 10px; padding-bottom: 60px; } ul { margin-left: 15px; } ul li { list-style: none; } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/styles/country.css ================================================ /* Countries*/ .country { max-width: 50rem; min-width: 50rem; height: 35rem; text-align: center; margin: 0.75rem auto; padding: 2rem; border-radius: 0.2rem; background: white; box-shadow: 0 0.1rem 1rem #cfc9c7; } .country:hover { box-shadow: 0 0.1rem 1rem #cfc9c7; -webkit-transition: all 0.2s ease-in; transform: scale(1.015); } .country_flag { height: 12rem; width: 20rem; text-align: center; margin: auto; } .country img { display: block; margin: auto; max-width: 100%; max-height: 100%; min-width: 100%; min-height: 100%; border-radius: 0.3rem; box-shadow: 0 0 0.6rem 0.2rem rgb(241, 225, 225); } .country_name { font-size: 1.6rem; color: #ffa500; letter-spacing: 0.075rem; font-weight: bolder; margin: 1rem; color: #414141; font-weight: 900; } .country p { font-size: 1.6rem; font-weight: 500; padding: 0.2rem; color: #747474; text-align: left; letter-spacing: 0.05rem; } .country span { font-weight: 600; } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/styles/footer.css ================================================ footer { position: absolute; bottom: 0; width: 100%; height: 60px; /* Height of the footer */ background: #6cf; } .footer-wrapper { font-weight: 400; text-align: center; line-height: 60px; } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/styles/header.css ================================================ header { background-color: #61dbfb; padding: 25; padding: 10px; } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/styles/index.css ================================================ /* == General style === */ /* This CSS has to be broken into small files */ @import './common.css'; @import './header.css'; @import './footer.css'; @import './user-card.css'; @import './country.css'; ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/styles/user-card.css ================================================ .user-card { margin-top: 10px; } .user-card > img { border-radius: 50%; width: 14%; } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/utils/display-date-and-time.js ================================================ export const showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return `${month} ${date}, ${year}` } ================================================ FILE: 10_React_Project_Folder_Structure/10_react_project_folder_structure_boilerplate/src/utils/hexadecimal-color-generator.js ================================================ // Hexadecimal color generator export const hexaColor = () => { let str = '0123456789abcdef' let color = '' for (let i = 0; i < 6; i++) { let index = Math.floor(Math.random() * str.length) color += str[index] } return '#' + color } ================================================ FILE: 11_Day_Events/11_events.md ================================================

    30 Days Of React: Events

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 10](../10_React_Project_Folder_Structure/10_react_project_folder_structure.md) | [Day 12 >>](../12_Day_Forms/12_forms.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_8.jpg) - [Events](#events) - [What is an event?](#what-is-an-event) - [Exercises](#exercises) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # Events ## What is an event? An event is an action or occurrence recognized by a software. To make an event more clear let's use the daily activities we do when we use a computer such as clicking on a button, hover on an image, pressing a keyboard, scrolling the mouse wheel and etc. In this section, we will focus only some of the mouse and keyboard events. The react documentation has already a detail note about [events](https://reactjs.org/docs/handling-events.html). Handling events in React is very similar to handling elements on DOM elements using pure JavaScript. Some of the syntax difference between handling event in React and pure JavaScript: - React events are named using camelCase, rather than lowercase. - With JSX you pass a function as the event handler, rather than a string. Let's see some examples to understand event handling. Event handling in HTML ```html 30 Days Of React App ``` In React, it is slightly different ```js import React from 'react' // if it is functional components const App = () => { const greetPeople = () => { alert('Welcome to 30 Days Of React Challenge') } return } ``` ```js import React, { Component } from 'react' // if it is functional components class App extends Component { greetPeople = () => { alert('Welcome to 30 Days Of React Challenge') } render() { return } } ``` Another difference between HTML and React event 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: Plain HTML ```html Click me ``` However, in React it could be as follows: ```js import React, { Component } from 'react' // if it is functional components class App extends Component { handleClick = () => { alert('Welcome to 30 Days Of React Challenge') } render() { return ( Click me ) } } ``` Event handling is a very vast topic and in this challenge we will focus on the most common event types. We may use the following mouse and keyboard events. _onMouseMove, onMouseEnter, onMouseLeave, onMouseOut, onClick, onKeyDown, onKeyPress, onKeyUp, onCopy, onCut, onDrag, onChange,onBlur,onInput, onSubmit_ Let's implement some more mouse and keyboard events. ```js // index.js import React, { Component } from 'react' import ReactDOM from 'react-dom' class App extends Component { state = { firstName: '', message: '', key: '', } handleClick = (e) => { // e gives an event object // check the value of e using console.log(e) this.setState({ message: 'Welcome to the world of events', }) } // triggered whenever the mouse moves handleMouseMove = (e) => { this.setState({ message: 'mouse is moving' }) } // to get value when an input field changes a value handleChange = (e) => { this.setState({ firstName: e.target.value, message: e.target.value, }) } // to get keyboard key code when an input field is pressed // it works with input and textarea handleKeyPress = (e) => { this.setState({ message: `${e.target.value} has been pressed and the keycode is` + e.charCode, }) } // Blurring happens when a mouse leave an input field handleBlur = (e) => { this.setState({ message: 'Input field has been blurred' }) } // This event triggers during a text copy handleCopy = (e) => { this.setState({ message: 'Using 30 Days Of React for commercial purpose is not allowed', }) } render() { return (

    Welcome to the World of Events

    Check copy right permission by copying this text

    {this.state.message}


    ) } } const rootElement = document.getElementById('root') // we render the JSX element using the ReactDOM package ReactDOM.render(, rootElement) ``` # Exercises ## Exercises: Level 1 1. What is an event? 2. What is the different between an HTML element event and React event? 3. Write at least 4 keyboard events? 4. Write at least 8 mouse events? 5. What are the most common mouse and keyboard events? 6. Write an event specific to input element? 7. Write an event specific to form element? 8. Display the coordinate of the view port when a mouse is moving on the body? 9. What is the difference between onInput, onChange and onBlur? 10. Where do we put the onSubmit event ? ## Exercises: Level 2 Implement the following using onMouseEnter event ![On mouse enter event](../images/react_event_on_mouse_enter.gif) ## Exercises: Level 3 Coming 🎉 CONGRATULATIONS ! 🎉 [<< Day 10](../10_React_Project_Folder_Structure/10_react_project_folder_structure.md) | [Day 12 >>](../12_Day_Forms/12_forms.md) ================================================ FILE: 11_Day_Events/11_events_boilerplate/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 11_Day_Events/11_events_boilerplate/README.md ================================================ # 30 Days of React App: Day 11 In the project directory, you can run to start the project ### `npm start` ================================================ FILE: 11_Day_Events/11_events_boilerplate/package.json ================================================ { "name": "30-days-of-react", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 11_Day_Events/11_events_boilerplate/public/index.html ================================================ 30 Days Of React App
    ================================================ FILE: 11_Day_Events/11_events_boilerplate/src/data/countries.js ================================================ export const countriesData = [ { name: 'Afghanistan', capital: 'Kabul', languages: ['Pashto', 'Uzbek', 'Turkmen'], population: 27657145, flag: 'https://restcountries.eu/data/afg.svg', currency: 'Afghan afghani', }, { name: 'Åland Islands', capital: 'Mariehamn', languages: ['Swedish'], population: 28875, flag: 'https://restcountries.eu/data/ala.svg', currency: 'Euro', }, { name: 'Albania', capital: 'Tirana', languages: ['Albanian'], population: 2886026, flag: 'https://restcountries.eu/data/alb.svg', currency: 'Albanian lek', }, { name: 'Algeria', capital: 'Algiers', languages: ['Arabic'], population: 40400000, flag: 'https://restcountries.eu/data/dza.svg', currency: 'Algerian dinar', }, { name: 'American Samoa', capital: 'Pago Pago', languages: ['English', 'Samoan'], population: 57100, flag: 'https://restcountries.eu/data/asm.svg', currency: 'United State Dollar', }, { name: 'Andorra', capital: 'Andorra la Vella', languages: ['Catalan'], population: 78014, flag: 'https://restcountries.eu/data/and.svg', currency: 'Euro', }, { name: 'Angola', capital: 'Luanda', languages: ['Portuguese'], population: 25868000, flag: 'https://restcountries.eu/data/ago.svg', currency: 'Angolan kwanza', }, { name: 'Anguilla', capital: 'The Valley', languages: ['English'], population: 13452, flag: 'https://restcountries.eu/data/aia.svg', currency: 'East Caribbean dollar', }, { name: 'Antarctica', capital: '', languages: ['English', 'Russian'], population: 1000, flag: 'https://restcountries.eu/data/ata.svg', currency: 'Australian dollar', }, { name: 'Antigua and Barbuda', capital: "Saint John's", languages: ['English'], population: 86295, flag: 'https://restcountries.eu/data/atg.svg', currency: 'East Caribbean dollar', }, { name: 'Argentina', capital: 'Buenos Aires', languages: ['Spanish', 'Guaraní'], population: 43590400, flag: 'https://restcountries.eu/data/arg.svg', currency: 'Argentine peso', }, { name: 'Armenia', capital: 'Yerevan', languages: ['Armenian', 'Russian'], population: 2994400, flag: 'https://restcountries.eu/data/arm.svg', currency: 'Armenian dram', }, { name: 'Aruba', capital: 'Oranjestad', languages: ['Dutch', '(Eastern) Punjabi'], population: 107394, flag: 'https://restcountries.eu/data/abw.svg', currency: 'Aruban florin', }, { name: 'Australia', capital: 'Canberra', languages: ['English'], population: 24117360, flag: 'https://restcountries.eu/data/aus.svg', currency: 'Australian dollar', }, { name: 'Austria', capital: 'Vienna', languages: ['German'], population: 8725931, flag: 'https://restcountries.eu/data/aut.svg', currency: 'Euro', }, { name: 'Azerbaijan', capital: 'Baku', languages: ['Azerbaijani'], population: 9730500, flag: 'https://restcountries.eu/data/aze.svg', currency: 'Azerbaijani manat', }, { name: 'Bahamas', capital: 'Nassau', languages: ['English'], population: 378040, flag: 'https://restcountries.eu/data/bhs.svg', currency: 'Bahamian dollar', }, { name: 'Bahrain', capital: 'Manama', languages: ['Arabic'], population: 1404900, flag: 'https://restcountries.eu/data/bhr.svg', currency: 'Bahraini dinar', }, { name: 'Bangladesh', capital: 'Dhaka', languages: ['Bengali'], population: 161006790, flag: 'https://restcountries.eu/data/bgd.svg', currency: 'Bangladeshi taka', }, { name: 'Barbados', capital: 'Bridgetown', languages: ['English'], population: 285000, flag: 'https://restcountries.eu/data/brb.svg', currency: 'Barbadian dollar', }, { name: 'Belarus', capital: 'Minsk', languages: ['Belarusian', 'Russian'], population: 9498700, flag: 'https://restcountries.eu/data/blr.svg', currency: 'New Belarusian ruble', }, { name: 'Belgium', capital: 'Brussels', languages: ['Dutch', 'French', 'German'], population: 11319511, flag: 'https://restcountries.eu/data/bel.svg', currency: 'Euro', }, { name: 'Belize', capital: 'Belmopan', languages: ['English', 'Spanish'], population: 370300, flag: 'https://restcountries.eu/data/blz.svg', currency: 'Belize dollar', }, { name: 'Benin', capital: 'Porto-Novo', languages: ['French'], population: 10653654, flag: 'https://restcountries.eu/data/ben.svg', currency: 'West African CFA franc', }, { name: 'Bermuda', capital: 'Hamilton', languages: ['English'], population: 61954, flag: 'https://restcountries.eu/data/bmu.svg', currency: 'Bermudian dollar', }, { name: 'Bhutan', capital: 'Thimphu', languages: ['Dzongkha'], population: 775620, flag: 'https://restcountries.eu/data/btn.svg', currency: 'Bhutanese ngultrum', }, { name: 'Bolivia (Plurinational State of)', capital: 'Sucre', languages: ['Spanish', 'Aymara', 'Quechua'], population: 10985059, flag: 'https://restcountries.eu/data/bol.svg', currency: 'Bolivian boliviano', }, { name: 'Bonaire, Sint Eustatius and Saba', capital: 'Kralendijk', languages: ['Dutch'], population: 17408, flag: 'https://restcountries.eu/data/bes.svg', currency: 'United States dollar', }, { name: 'Bosnia and Herzegovina', capital: 'Sarajevo', languages: ['Bosnian', 'Croatian', 'Serbian'], population: 3531159, flag: 'https://restcountries.eu/data/bih.svg', currency: 'Bosnia and Herzegovina convertible mark', }, { name: 'Botswana', capital: 'Gaborone', languages: ['English', 'Tswana'], population: 2141206, flag: 'https://restcountries.eu/data/bwa.svg', currency: 'Botswana pula', }, { name: 'Bouvet Island', capital: '', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 0, flag: 'https://restcountries.eu/data/bvt.svg', currency: 'Norwegian krone', }, { name: 'Brazil', capital: 'Brasília', languages: ['Portuguese'], population: 206135893, flag: 'https://restcountries.eu/data/bra.svg', currency: 'Brazilian real', }, { name: 'British Indian Ocean Territory', capital: 'Diego Garcia', languages: ['English'], population: 3000, flag: 'https://restcountries.eu/data/iot.svg', currency: 'United States dollar', }, { name: 'United States Minor Outlying Islands', capital: '', languages: ['English'], population: 300, flag: 'https://restcountries.eu/data/umi.svg', currency: 'United States Dollar', }, { name: 'Virgin Islands (British)', capital: 'Road Town', languages: ['English'], population: 28514, flag: 'https://restcountries.eu/data/vgb.svg', currency: '[D]', }, { name: 'Virgin Islands (U.S.)', capital: 'Charlotte Amalie', languages: ['English'], population: 114743, flag: 'https://restcountries.eu/data/vir.svg', currency: 'United States dollar', }, { name: 'Brunei Darussalam', capital: 'Bandar Seri Begawan', languages: ['Malay'], population: 411900, flag: 'https://restcountries.eu/data/brn.svg', currency: 'Brunei dollar', }, { name: 'Bulgaria', capital: 'Sofia', languages: ['Bulgarian'], population: 7153784, flag: 'https://restcountries.eu/data/bgr.svg', currency: 'Bulgarian lev', }, { name: 'Burkina Faso', capital: 'Ouagadougou', languages: ['French', 'Fula'], population: 19034397, flag: 'https://restcountries.eu/data/bfa.svg', currency: 'West African CFA franc', }, { name: 'Burundi', capital: 'Bujumbura', languages: ['French', 'Kirundi'], population: 10114505, flag: 'https://restcountries.eu/data/bdi.svg', currency: 'Burundian franc', }, { name: 'Cambodia', capital: 'Phnom Penh', languages: ['Khmer'], population: 15626444, flag: 'https://restcountries.eu/data/khm.svg', currency: 'Cambodian riel', }, { name: 'Cameroon', capital: 'Yaoundé', languages: ['English', 'French'], population: 22709892, flag: 'https://restcountries.eu/data/cmr.svg', currency: 'Central African CFA franc', }, { name: 'Canada', capital: 'Ottawa', languages: ['English', 'French'], population: 36155487, flag: 'https://restcountries.eu/data/can.svg', currency: 'Canadian dollar', }, { name: 'Cabo Verde', capital: 'Praia', languages: ['Portuguese'], population: 531239, flag: 'https://restcountries.eu/data/cpv.svg', currency: 'Cape Verdean escudo', }, { name: 'Cayman Islands', capital: 'George Town', languages: ['English'], population: 58238, flag: 'https://restcountries.eu/data/cym.svg', currency: 'Cayman Islands dollar', }, { name: 'Central African Republic', capital: 'Bangui', languages: ['French', 'Sango'], population: 4998000, flag: 'https://restcountries.eu/data/caf.svg', currency: 'Central African CFA franc', }, { name: 'Chad', capital: "N'Djamena", languages: ['French', 'Arabic'], population: 14497000, flag: 'https://restcountries.eu/data/tcd.svg', currency: 'Central African CFA franc', }, { name: 'Chile', capital: 'Santiago', languages: ['Spanish'], population: 18191900, flag: 'https://restcountries.eu/data/chl.svg', currency: 'Chilean peso', }, { name: 'China', capital: 'Beijing', languages: ['Chinese'], population: 1377422166, flag: 'https://restcountries.eu/data/chn.svg', currency: 'Chinese yuan', }, { name: 'Christmas Island', capital: 'Flying Fish Cove', languages: ['English'], population: 2072, flag: 'https://restcountries.eu/data/cxr.svg', currency: 'Australian dollar', }, { name: 'Cocos (Keeling) Islands', capital: 'West Island', languages: ['English'], population: 550, flag: 'https://restcountries.eu/data/cck.svg', currency: 'Australian dollar', }, { name: 'Colombia', capital: 'Bogotá', languages: ['Spanish'], population: 48759958, flag: 'https://restcountries.eu/data/col.svg', currency: 'Colombian peso', }, { name: 'Comoros', capital: 'Moroni', languages: ['Arabic', 'French'], population: 806153, flag: 'https://restcountries.eu/data/com.svg', currency: 'Comorian franc', }, { name: 'Congo', capital: 'Brazzaville', languages: ['French', 'Lingala'], population: 4741000, flag: 'https://restcountries.eu/data/cog.svg', currency: 'Central African CFA franc', }, { name: 'Congo (Democratic Republic of the)', capital: 'Kinshasa', languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], population: 85026000, flag: 'https://restcountries.eu/data/cod.svg', currency: 'Congolese franc', }, { name: 'Cook Islands', capital: 'Avarua', languages: ['English'], population: 18100, flag: 'https://restcountries.eu/data/cok.svg', currency: 'New Zealand dollar', }, { name: 'Costa Rica', capital: 'San José', languages: ['Spanish'], population: 4890379, flag: 'https://restcountries.eu/data/cri.svg', currency: 'Costa Rican colón', }, { name: 'Croatia', capital: 'Zagreb', languages: ['Croatian'], population: 4190669, flag: 'https://restcountries.eu/data/hrv.svg', currency: 'Croatian kuna', }, { name: 'Cuba', capital: 'Havana', languages: ['Spanish'], population: 11239004, flag: 'https://restcountries.eu/data/cub.svg', currency: 'Cuban convertible peso', }, { name: 'Curaçao', capital: 'Willemstad', languages: ['Dutch', '(Eastern) Punjabi', 'English'], population: 154843, flag: 'https://restcountries.eu/data/cuw.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Cyprus', capital: 'Nicosia', languages: ['Greek (modern)', 'Turkish', 'Armenian'], population: 847000, flag: 'https://restcountries.eu/data/cyp.svg', currency: 'Euro', }, { name: 'Czech Republic', capital: 'Prague', languages: ['Czech', 'Slovak'], population: 10558524, flag: 'https://restcountries.eu/data/cze.svg', currency: 'Czech koruna', }, { name: 'Denmark', capital: 'Copenhagen', languages: ['Danish'], population: 5717014, flag: 'https://restcountries.eu/data/dnk.svg', currency: 'Danish krone', }, { name: 'Djibouti', capital: 'Djibouti', languages: ['French', 'Arabic'], population: 900000, flag: 'https://restcountries.eu/data/dji.svg', currency: 'Djiboutian franc', }, { name: 'Dominica', capital: 'Roseau', languages: ['English'], population: 71293, flag: 'https://restcountries.eu/data/dma.svg', currency: 'East Caribbean dollar', }, { name: 'Dominican Republic', capital: 'Santo Domingo', languages: ['Spanish'], population: 10075045, flag: 'https://restcountries.eu/data/dom.svg', currency: 'Dominican peso', }, { name: 'Ecuador', capital: 'Quito', languages: ['Spanish'], population: 16545799, flag: 'https://restcountries.eu/data/ecu.svg', currency: 'United States dollar', }, { name: 'Egypt', capital: 'Cairo', languages: ['Arabic'], population: 91290000, flag: 'https://restcountries.eu/data/egy.svg', currency: 'Egyptian pound', }, { name: 'El Salvador', capital: 'San Salvador', languages: ['Spanish'], population: 6520675, flag: 'https://restcountries.eu/data/slv.svg', currency: 'United States dollar', }, { name: 'Equatorial Guinea', capital: 'Malabo', languages: ['Spanish', 'French'], population: 1222442, flag: 'https://restcountries.eu/data/gnq.svg', currency: 'Central African CFA franc', }, { name: 'Eritrea', capital: 'Asmara', languages: ['Tigrinya', 'Arabic', 'English'], population: 5352000, flag: 'https://restcountries.eu/data/eri.svg', currency: 'Eritrean nakfa', }, { name: 'Estonia', capital: 'Tallinn', languages: ['Estonian'], population: 1315944, flag: 'https://restcountries.eu/data/est.svg', currency: 'Euro', }, { name: 'Ethiopia', capital: 'Addis Ababa', languages: ['Amharic'], population: 92206005, flag: 'https://restcountries.eu/data/eth.svg', currency: 'Ethiopian birr', }, { name: 'Falkland Islands (Malvinas)', capital: 'Stanley', languages: ['English'], population: 2563, flag: 'https://restcountries.eu/data/flk.svg', currency: 'Falkland Islands pound', }, { name: 'Faroe Islands', capital: 'Tórshavn', languages: ['Faroese'], population: 49376, flag: 'https://restcountries.eu/data/fro.svg', currency: 'Danish krone', }, { name: 'Fiji', capital: 'Suva', languages: ['English', 'Fijian', 'Hindi', 'Urdu'], population: 867000, flag: 'https://restcountries.eu/data/fji.svg', currency: 'Fijian dollar', }, { name: 'Finland', capital: 'Helsinki', languages: ['Finnish', 'Swedish'], population: 5491817, flag: 'https://restcountries.eu/data/fin.svg', currency: 'Euro', }, { name: 'France', capital: 'Paris', languages: ['French'], population: 66710000, flag: 'https://restcountries.eu/data/fra.svg', currency: 'Euro', }, { name: 'French Guiana', capital: 'Cayenne', languages: ['French'], population: 254541, flag: 'https://restcountries.eu/data/guf.svg', currency: 'Euro', }, { name: 'French Polynesia', capital: 'Papeetē', languages: ['French'], population: 271800, flag: 'https://restcountries.eu/data/pyf.svg', currency: 'CFP franc', }, { name: 'French Southern Territories', capital: 'Port-aux-Français', languages: ['French'], population: 140, flag: 'https://restcountries.eu/data/atf.svg', currency: 'Euro', }, { name: 'Gabon', capital: 'Libreville', languages: ['French'], population: 1802278, flag: 'https://restcountries.eu/data/gab.svg', currency: 'Central African CFA franc', }, { name: 'Gambia', capital: 'Banjul', languages: ['English'], population: 1882450, flag: 'https://restcountries.eu/data/gmb.svg', currency: 'Gambian dalasi', }, { name: 'Georgia', capital: 'Tbilisi', languages: ['Georgian'], population: 3720400, flag: 'https://restcountries.eu/data/geo.svg', currency: 'Georgian Lari', }, { name: 'Germany', capital: 'Berlin', languages: ['German'], population: 81770900, flag: 'https://restcountries.eu/data/deu.svg', currency: 'Euro', }, { name: 'Ghana', capital: 'Accra', languages: ['English'], population: 27670174, flag: 'https://restcountries.eu/data/gha.svg', currency: 'Ghanaian cedi', }, { name: 'Gibraltar', capital: 'Gibraltar', languages: ['English'], population: 33140, flag: 'https://restcountries.eu/data/gib.svg', currency: 'Gibraltar pound', }, { name: 'Greece', capital: 'Athens', languages: ['Greek (modern)'], population: 10858018, flag: 'https://restcountries.eu/data/grc.svg', currency: 'Euro', }, { name: 'Greenland', capital: 'Nuuk', languages: ['Kalaallisut'], population: 55847, flag: 'https://restcountries.eu/data/grl.svg', currency: 'Danish krone', }, { name: 'Grenada', capital: "St. George's", languages: ['English'], population: 103328, flag: 'https://restcountries.eu/data/grd.svg', currency: 'East Caribbean dollar', }, { name: 'Guadeloupe', capital: 'Basse-Terre', languages: ['French'], population: 400132, flag: 'https://restcountries.eu/data/glp.svg', currency: 'Euro', }, { name: 'Guam', capital: 'Hagåtña', languages: ['English', 'Chamorro', 'Spanish'], population: 184200, flag: 'https://restcountries.eu/data/gum.svg', currency: 'United States dollar', }, { name: 'Guatemala', capital: 'Guatemala City', languages: ['Spanish'], population: 16176133, flag: 'https://restcountries.eu/data/gtm.svg', currency: 'Guatemalan quetzal', }, { name: 'Guernsey', capital: 'St. Peter Port', languages: ['English', 'French'], population: 62999, flag: 'https://restcountries.eu/data/ggy.svg', currency: 'British pound', }, { name: 'Guinea', capital: 'Conakry', languages: ['French', 'Fula'], population: 12947000, flag: 'https://restcountries.eu/data/gin.svg', currency: 'Guinean franc', }, { name: 'Guinea-Bissau', capital: 'Bissau', languages: ['Portuguese'], population: 1547777, flag: 'https://restcountries.eu/data/gnb.svg', currency: 'West African CFA franc', }, { name: 'Guyana', capital: 'Georgetown', languages: ['English'], population: 746900, flag: 'https://restcountries.eu/data/guy.svg', currency: 'Guyanese dollar', }, { name: 'Haiti', capital: 'Port-au-Prince', languages: ['French', 'Haitian'], population: 11078033, flag: 'https://restcountries.eu/data/hti.svg', currency: 'Haitian gourde', }, { name: 'Heard Island and McDonald Islands', capital: '', languages: ['English'], population: 0, flag: 'https://restcountries.eu/data/hmd.svg', currency: 'Australian dollar', }, { name: 'Holy See', capital: 'Rome', languages: ['Latin', 'Italian', 'French', 'German'], population: 451, flag: 'https://restcountries.eu/data/vat.svg', currency: 'Euro', }, { name: 'Honduras', capital: 'Tegucigalpa', languages: ['Spanish'], population: 8576532, flag: 'https://restcountries.eu/data/hnd.svg', currency: 'Honduran lempira', }, { name: 'Hong Kong', capital: 'City of Victoria', languages: ['English', 'Chinese'], population: 7324300, flag: 'https://restcountries.eu/data/hkg.svg', currency: 'Hong Kong dollar', }, { name: 'Hungary', capital: 'Budapest', languages: ['Hungarian'], population: 9823000, flag: 'https://restcountries.eu/data/hun.svg', currency: 'Hungarian forint', }, { name: 'Iceland', capital: 'Reykjavík', languages: ['Icelandic'], population: 334300, flag: 'https://restcountries.eu/data/isl.svg', currency: 'Icelandic króna', }, { name: 'India', capital: 'New Delhi', languages: ['Hindi', 'English'], population: 1295210000, flag: 'https://restcountries.eu/data/ind.svg', currency: 'Indian rupee', }, { name: 'Indonesia', capital: 'Jakarta', languages: ['Indonesian'], population: 258705000, flag: 'https://restcountries.eu/data/idn.svg', currency: 'Indonesian rupiah', }, { name: "Côte d'Ivoire", capital: 'Yamoussoukro', languages: ['French'], population: 22671331, flag: 'https://restcountries.eu/data/civ.svg', currency: 'West African CFA franc', }, { name: 'Iran (Islamic Republic of)', capital: 'Tehran', languages: ['Persian (Farsi)'], population: 79369900, flag: 'https://restcountries.eu/data/irn.svg', currency: 'Iranian rial', }, { name: 'Iraq', capital: 'Baghdad', languages: ['Arabic', 'Kurdish'], population: 37883543, flag: 'https://restcountries.eu/data/irq.svg', currency: 'Iraqi dinar', }, { name: 'Ireland', capital: 'Dublin', languages: ['Irish', 'English'], population: 6378000, flag: 'https://restcountries.eu/data/irl.svg', currency: 'Euro', }, { name: 'Isle of Man', capital: 'Douglas', languages: ['English', 'Manx'], population: 84497, flag: 'https://restcountries.eu/data/imn.svg', currency: 'British pound', }, { name: 'Israel', capital: 'Jerusalem', languages: ['Hebrew (modern)', 'Arabic'], population: 8527400, flag: 'https://restcountries.eu/data/isr.svg', currency: 'Israeli new shekel', }, { name: 'Italy', capital: 'Rome', languages: ['Italian'], population: 60665551, flag: 'https://restcountries.eu/data/ita.svg', currency: 'Euro', }, { name: 'Jamaica', capital: 'Kingston', languages: ['English'], population: 2723246, flag: 'https://restcountries.eu/data/jam.svg', currency: 'Jamaican dollar', }, { name: 'Japan', capital: 'Tokyo', languages: ['Japanese'], population: 126960000, flag: 'https://restcountries.eu/data/jpn.svg', currency: 'Japanese yen', }, { name: 'Jersey', capital: 'Saint Helier', languages: ['English', 'French'], population: 100800, flag: 'https://restcountries.eu/data/jey.svg', currency: 'British pound', }, { name: 'Jordan', capital: 'Amman', languages: ['Arabic'], population: 9531712, flag: 'https://restcountries.eu/data/jor.svg', currency: 'Jordanian dinar', }, { name: 'Kazakhstan', capital: 'Astana', languages: ['Kazakh', 'Russian'], population: 17753200, flag: 'https://restcountries.eu/data/kaz.svg', currency: 'Kazakhstani tenge', }, { name: 'Kenya', capital: 'Nairobi', languages: ['English', 'Swahili'], population: 47251000, flag: 'https://restcountries.eu/data/ken.svg', currency: 'Kenyan shilling', }, { name: 'Kiribati', capital: 'South Tarawa', languages: ['English'], population: 113400, flag: 'https://restcountries.eu/data/kir.svg', currency: 'Australian dollar', }, { name: 'Kuwait', capital: 'Kuwait City', languages: ['Arabic'], population: 4183658, flag: 'https://restcountries.eu/data/kwt.svg', currency: 'Kuwaiti dinar', }, { name: 'Kyrgyzstan', capital: 'Bishkek', languages: ['Kyrgyz', 'Russian'], population: 6047800, flag: 'https://restcountries.eu/data/kgz.svg', currency: 'Kyrgyzstani som', }, { name: "Lao People's Democratic Republic", capital: 'Vientiane', languages: ['Lao'], population: 6492400, flag: 'https://restcountries.eu/data/lao.svg', currency: 'Lao kip', }, { name: 'Latvia', capital: 'Riga', languages: ['Latvian'], population: 1961600, flag: 'https://restcountries.eu/data/lva.svg', currency: 'Euro', }, { name: 'Lebanon', capital: 'Beirut', languages: ['Arabic', 'French'], population: 5988000, flag: 'https://restcountries.eu/data/lbn.svg', currency: 'Lebanese pound', }, { name: 'Lesotho', capital: 'Maseru', languages: ['English', 'Southern Sotho'], population: 1894194, flag: 'https://restcountries.eu/data/lso.svg', currency: 'Lesotho loti', }, { name: 'Liberia', capital: 'Monrovia', languages: ['English'], population: 4615000, flag: 'https://restcountries.eu/data/lbr.svg', currency: 'Liberian dollar', }, { name: 'Libya', capital: 'Tripoli', languages: ['Arabic'], population: 6385000, flag: 'https://restcountries.eu/data/lby.svg', currency: 'Libyan dinar', }, { name: 'Liechtenstein', capital: 'Vaduz', languages: ['German'], population: 37623, flag: 'https://restcountries.eu/data/lie.svg', currency: 'Swiss franc', }, { name: 'Lithuania', capital: 'Vilnius', languages: ['Lithuanian'], population: 2872294, flag: 'https://restcountries.eu/data/ltu.svg', currency: 'Euro', }, { name: 'Luxembourg', capital: 'Luxembourg', languages: ['French', 'German', 'Luxembourgish'], population: 576200, flag: 'https://restcountries.eu/data/lux.svg', currency: 'Euro', }, { name: 'Macao', capital: '', languages: ['Chinese', 'Portuguese'], population: 649100, flag: 'https://restcountries.eu/data/mac.svg', currency: 'Macanese pataca', }, { name: 'Macedonia (the former Yugoslav Republic of)', capital: 'Skopje', languages: ['Macedonian'], population: 2058539, flag: 'https://restcountries.eu/data/mkd.svg', currency: 'Macedonian denar', }, { name: 'Madagascar', capital: 'Antananarivo', languages: ['French', 'Malagasy'], population: 22434363, flag: 'https://restcountries.eu/data/mdg.svg', currency: 'Malagasy ariary', }, { name: 'Malawi', capital: 'Lilongwe', languages: ['English', 'Chichewa'], population: 16832910, flag: 'https://restcountries.eu/data/mwi.svg', currency: 'Malawian kwacha', }, { name: 'Malaysia', capital: 'Kuala Lumpur', languages: ['Malaysian'], population: 31405416, flag: 'https://restcountries.eu/data/mys.svg', currency: 'Malaysian ringgit', }, { name: 'Maldives', capital: 'Malé', languages: ['Divehi'], population: 344023, flag: 'https://restcountries.eu/data/mdv.svg', currency: 'Maldivian rufiyaa', }, { name: 'Mali', capital: 'Bamako', languages: ['French'], population: 18135000, flag: 'https://restcountries.eu/data/mli.svg', currency: 'West African CFA franc', }, { name: 'Malta', capital: 'Valletta', languages: ['Maltese', 'English'], population: 425384, flag: 'https://restcountries.eu/data/mlt.svg', currency: 'Euro', }, { name: 'Marshall Islands', capital: 'Majuro', languages: ['English', 'Marshallese'], population: 54880, flag: 'https://restcountries.eu/data/mhl.svg', currency: 'United States dollar', }, { name: 'Martinique', capital: 'Fort-de-France', languages: ['French'], population: 378243, flag: 'https://restcountries.eu/data/mtq.svg', currency: 'Euro', }, { name: 'Mauritania', capital: 'Nouakchott', languages: ['Arabic'], population: 3718678, flag: 'https://restcountries.eu/data/mrt.svg', currency: 'Mauritanian ouguiya', }, { name: 'Mauritius', capital: 'Port Louis', languages: ['English'], population: 1262879, flag: 'https://restcountries.eu/data/mus.svg', currency: 'Mauritian rupee', }, { name: 'Mayotte', capital: 'Mamoudzou', languages: ['French'], population: 226915, flag: 'https://restcountries.eu/data/myt.svg', currency: 'Euro', }, { name: 'Mexico', capital: 'Mexico City', languages: ['Spanish'], population: 122273473, flag: 'https://restcountries.eu/data/mex.svg', currency: 'Mexican peso', }, { name: 'Micronesia (Federated States of)', capital: 'Palikir', languages: ['English'], population: 102800, flag: 'https://restcountries.eu/data/fsm.svg', currency: '[D]', }, { name: 'Moldova (Republic of)', capital: 'Chișinău', languages: ['Romanian'], population: 3553100, flag: 'https://restcountries.eu/data/mda.svg', currency: 'Moldovan leu', }, { name: 'Monaco', capital: 'Monaco', languages: ['French'], population: 38400, flag: 'https://restcountries.eu/data/mco.svg', currency: 'Euro', }, { name: 'Mongolia', capital: 'Ulan Bator', languages: ['Mongolian'], population: 3093100, flag: 'https://restcountries.eu/data/mng.svg', currency: 'Mongolian tögrög', }, { name: 'Montenegro', capital: 'Podgorica', languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], population: 621810, flag: 'https://restcountries.eu/data/mne.svg', currency: 'Euro', }, { name: 'Montserrat', capital: 'Plymouth', languages: ['English'], population: 4922, flag: 'https://restcountries.eu/data/msr.svg', currency: 'East Caribbean dollar', }, { name: 'Morocco', capital: 'Rabat', languages: ['Arabic'], population: 33337529, flag: 'https://restcountries.eu/data/mar.svg', currency: 'Moroccan dirham', }, { name: 'Mozambique', capital: 'Maputo', languages: ['Portuguese'], population: 26423700, flag: 'https://restcountries.eu/data/moz.svg', currency: 'Mozambican metical', }, { name: 'Myanmar', capital: 'Naypyidaw', languages: ['Burmese'], population: 51419420, flag: 'https://restcountries.eu/data/mmr.svg', currency: 'Burmese kyat', }, { name: 'Namibia', capital: 'Windhoek', languages: ['English', 'Afrikaans'], population: 2324388, flag: 'https://restcountries.eu/data/nam.svg', currency: 'Namibian dollar', }, { name: 'Nauru', capital: 'Yaren', languages: ['English', 'Nauruan'], population: 10084, flag: 'https://restcountries.eu/data/nru.svg', currency: 'Australian dollar', }, { name: 'Nepal', capital: 'Kathmandu', languages: ['Nepali'], population: 28431500, flag: 'https://restcountries.eu/data/npl.svg', currency: 'Nepalese rupee', }, { name: 'Netherlands', capital: 'Amsterdam', languages: ['Dutch'], population: 17019800, flag: 'https://restcountries.eu/data/nld.svg', currency: 'Euro', }, { name: 'New Caledonia', capital: 'Nouméa', languages: ['French'], population: 268767, flag: 'https://restcountries.eu/data/ncl.svg', currency: 'CFP franc', }, { name: 'New Zealand', capital: 'Wellington', languages: ['English', 'Māori'], population: 4697854, flag: 'https://restcountries.eu/data/nzl.svg', currency: 'New Zealand dollar', }, { name: 'Nicaragua', capital: 'Managua', languages: ['Spanish'], population: 6262703, flag: 'https://restcountries.eu/data/nic.svg', currency: 'Nicaraguan córdoba', }, { name: 'Niger', capital: 'Niamey', languages: ['French'], population: 20715000, flag: 'https://restcountries.eu/data/ner.svg', currency: 'West African CFA franc', }, { name: 'Nigeria', capital: 'Abuja', languages: ['English'], population: 186988000, flag: 'https://restcountries.eu/data/nga.svg', currency: 'Nigerian naira', }, { name: 'Niue', capital: 'Alofi', languages: ['English'], population: 1470, flag: 'https://restcountries.eu/data/niu.svg', currency: 'New Zealand dollar', }, { name: 'Norfolk Island', capital: 'Kingston', languages: ['English'], population: 2302, flag: 'https://restcountries.eu/data/nfk.svg', currency: 'Australian dollar', }, { name: "Korea (Democratic People's Republic of)", capital: 'Pyongyang', languages: ['Korean'], population: 25281000, flag: 'https://restcountries.eu/data/prk.svg', currency: 'North Korean won', }, { name: 'Northern Mariana Islands', capital: 'Saipan', languages: ['English', 'Chamorro'], population: 56940, flag: 'https://restcountries.eu/data/mnp.svg', currency: 'United States dollar', }, { name: 'Norway', capital: 'Oslo', languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], population: 5223256, flag: 'https://restcountries.eu/data/nor.svg', currency: 'Norwegian krone', }, { name: 'Oman', capital: 'Muscat', languages: ['Arabic'], population: 4420133, flag: 'https://restcountries.eu/data/omn.svg', currency: 'Omani rial', }, { name: 'Pakistan', capital: 'Islamabad', languages: ['English', 'Urdu'], population: 194125062, flag: 'https://restcountries.eu/data/pak.svg', currency: 'Pakistani rupee', }, { name: 'Palau', capital: 'Ngerulmud', languages: ['English'], population: 17950, flag: 'https://restcountries.eu/data/plw.svg', currency: '[E]', }, { name: 'Palestine, State of', capital: 'Ramallah', languages: ['Arabic'], population: 4682467, flag: 'https://restcountries.eu/data/pse.svg', currency: 'Israeli new sheqel', }, { name: 'Panama', capital: 'Panama City', languages: ['Spanish'], population: 3814672, flag: 'https://restcountries.eu/data/pan.svg', currency: 'Panamanian balboa', }, { name: 'Papua New Guinea', capital: 'Port Moresby', languages: ['English'], population: 8083700, flag: 'https://restcountries.eu/data/png.svg', currency: 'Papua New Guinean kina', }, { name: 'Paraguay', capital: 'Asunción', languages: ['Spanish', 'Guaraní'], population: 6854536, flag: 'https://restcountries.eu/data/pry.svg', currency: 'Paraguayan guaraní', }, { name: 'Peru', capital: 'Lima', languages: ['Spanish'], population: 31488700, flag: 'https://restcountries.eu/data/per.svg', currency: 'Peruvian sol', }, { name: 'Philippines', capital: 'Manila', languages: ['English'], population: 103279800, flag: 'https://restcountries.eu/data/phl.svg', currency: 'Philippine peso', }, { name: 'Pitcairn', capital: 'Adamstown', languages: ['English'], population: 56, flag: 'https://restcountries.eu/data/pcn.svg', currency: 'New Zealand dollar', }, { name: 'Poland', capital: 'Warsaw', languages: ['Polish'], population: 38437239, flag: 'https://restcountries.eu/data/pol.svg', currency: 'Polish złoty', }, { name: 'Portugal', capital: 'Lisbon', languages: ['Portuguese'], population: 10374822, flag: 'https://restcountries.eu/data/prt.svg', currency: 'Euro', }, { name: 'Puerto Rico', capital: 'San Juan', languages: ['Spanish', 'English'], population: 3474182, flag: 'https://restcountries.eu/data/pri.svg', currency: 'United States dollar', }, { name: 'Qatar', capital: 'Doha', languages: ['Arabic'], population: 2587564, flag: 'https://restcountries.eu/data/qat.svg', currency: 'Qatari riyal', }, { name: 'Republic of Kosovo', capital: 'Pristina', languages: ['Albanian', 'Serbian'], population: 1733842, flag: 'https://restcountries.eu/data/kos.svg', currency: 'Euro', }, { name: 'Réunion', capital: 'Saint-Denis', languages: ['French'], population: 840974, flag: 'https://restcountries.eu/data/reu.svg', currency: 'Euro', }, { name: 'Romania', capital: 'Bucharest', languages: ['Romanian'], population: 19861408, flag: 'https://restcountries.eu/data/rou.svg', currency: 'Romanian leu', }, { name: 'Russian Federation', capital: 'Moscow', languages: ['Russian'], population: 146599183, flag: 'https://restcountries.eu/data/rus.svg', currency: 'Russian ruble', }, { name: 'Rwanda', capital: 'Kigali', languages: ['Kinyarwanda', 'English', 'French'], population: 11553188, flag: 'https://restcountries.eu/data/rwa.svg', currency: 'Rwandan franc', }, { name: 'Saint Barthélemy', capital: 'Gustavia', languages: ['French'], population: 9417, flag: 'https://restcountries.eu/data/blm.svg', currency: 'Euro', }, { name: 'Saint Helena, Ascension and Tristan da Cunha', capital: 'Jamestown', languages: ['English'], population: 4255, flag: 'https://restcountries.eu/data/shn.svg', currency: 'Saint Helena pound', }, { name: 'Saint Kitts and Nevis', capital: 'Basseterre', languages: ['English'], population: 46204, flag: 'https://restcountries.eu/data/kna.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Lucia', capital: 'Castries', languages: ['English'], population: 186000, flag: 'https://restcountries.eu/data/lca.svg', currency: 'East Caribbean dollar', }, { name: 'Saint Martin (French part)', capital: 'Marigot', languages: ['English', 'French', 'Dutch'], population: 36979, flag: 'https://restcountries.eu/data/maf.svg', currency: 'Euro', }, { name: 'Saint Pierre and Miquelon', capital: 'Saint-Pierre', languages: ['French'], population: 6069, flag: 'https://restcountries.eu/data/spm.svg', currency: 'Euro', }, { name: 'Saint Vincent and the Grenadines', capital: 'Kingstown', languages: ['English'], population: 109991, flag: 'https://restcountries.eu/data/vct.svg', currency: 'East Caribbean dollar', }, { name: 'Samoa', capital: 'Apia', languages: ['Samoan', 'English'], population: 194899, flag: 'https://restcountries.eu/data/wsm.svg', currency: 'Samoan tālā', }, { name: 'San Marino', capital: 'City of San Marino', languages: ['Italian'], population: 33005, flag: 'https://restcountries.eu/data/smr.svg', currency: 'Euro', }, { name: 'Sao Tome and Principe', capital: 'São Tomé', languages: ['Portuguese'], population: 187356, flag: 'https://restcountries.eu/data/stp.svg', currency: 'São Tomé and Príncipe dobra', }, { name: 'Saudi Arabia', capital: 'Riyadh', languages: ['Arabic'], population: 32248200, flag: 'https://restcountries.eu/data/sau.svg', currency: 'Saudi riyal', }, { name: 'Senegal', capital: 'Dakar', languages: ['French'], population: 14799859, flag: 'https://restcountries.eu/data/sen.svg', currency: 'West African CFA franc', }, { name: 'Serbia', capital: 'Belgrade', languages: ['Serbian'], population: 7076372, flag: 'https://restcountries.eu/data/srb.svg', currency: 'Serbian dinar', }, { name: 'Seychelles', capital: 'Victoria', languages: ['French', 'English'], population: 91400, flag: 'https://restcountries.eu/data/syc.svg', currency: 'Seychellois rupee', }, { name: 'Sierra Leone', capital: 'Freetown', languages: ['English'], population: 7075641, flag: 'https://restcountries.eu/data/sle.svg', currency: 'Sierra Leonean leone', }, { name: 'Singapore', capital: 'Singapore', languages: ['English', 'Malay', 'Tamil', 'Chinese'], population: 5535000, flag: 'https://restcountries.eu/data/sgp.svg', currency: 'Brunei dollar', }, { name: 'Sint Maarten (Dutch part)', capital: 'Philipsburg', languages: ['Dutch', 'English'], population: 38247, flag: 'https://restcountries.eu/data/sxm.svg', currency: 'Netherlands Antillean guilder', }, { name: 'Slovakia', capital: 'Bratislava', languages: ['Slovak'], population: 5426252, flag: 'https://restcountries.eu/data/svk.svg', currency: 'Euro', }, { name: 'Slovenia', capital: 'Ljubljana', languages: ['Slovene'], population: 2064188, flag: 'https://restcountries.eu/data/svn.svg', currency: 'Euro', }, { name: 'Solomon Islands', capital: 'Honiara', languages: ['English'], population: 642000, flag: 'https://restcountries.eu/data/slb.svg', currency: 'Solomon Islands dollar', }, { name: 'Somalia', capital: 'Mogadishu', languages: ['Somali', 'Arabic'], population: 11079000, flag: 'https://restcountries.eu/data/som.svg', currency: 'Somali shilling', }, { name: 'South Africa', capital: 'Pretoria', languages: [ 'Afrikaans', 'English', 'Southern Ndebele', 'Southern Sotho', 'Swati', 'Tswana', 'Tsonga', 'Venda', 'Xhosa', 'Zulu', ], population: 55653654, flag: 'https://restcountries.eu/data/zaf.svg', currency: 'South African rand', }, { name: 'South Georgia and the South Sandwich Islands', capital: 'King Edward Point', languages: ['English'], population: 30, flag: 'https://restcountries.eu/data/sgs.svg', currency: 'British pound', }, { name: 'Korea (Republic of)', capital: 'Seoul', languages: ['Korean'], population: 50801405, flag: 'https://restcountries.eu/data/kor.svg', currency: 'South Korean won', }, { name: 'South Sudan', capital: 'Juba', languages: ['English'], population: 12131000, flag: 'https://restcountries.eu/data/ssd.svg', currency: 'South Sudanese pound', }, { name: 'Spain', capital: 'Madrid', languages: ['Spanish'], population: 46438422, flag: 'https://restcountries.eu/data/esp.svg', currency: 'Euro', }, { name: 'Sri Lanka', capital: 'Colombo', languages: ['Sinhalese', 'Tamil'], population: 20966000, flag: 'https://restcountries.eu/data/lka.svg', currency: 'Sri Lankan rupee', }, { name: 'Sudan', capital: 'Khartoum', languages: ['Arabic', 'English'], population: 39598700, flag: 'https://restcountries.eu/data/sdn.svg', currency: 'Sudanese pound', }, { name: 'Suriname', capital: 'Paramaribo', languages: ['Dutch'], population: 541638, flag: 'https://restcountries.eu/data/sur.svg', currency: 'Surinamese dollar', }, { name: 'Svalbard and Jan Mayen', capital: 'Longyearbyen', languages: ['Norwegian'], population: 2562, flag: 'https://restcountries.eu/data/sjm.svg', currency: 'Norwegian krone', }, { name: 'Swaziland', capital: 'Lobamba', languages: ['English', 'Swati'], population: 1132657, flag: 'https://restcountries.eu/data/swz.svg', currency: 'Swazi lilangeni', }, { name: 'Sweden', capital: 'Stockholm', languages: ['Swedish'], population: 9894888, flag: 'https://restcountries.eu/data/swe.svg', currency: 'Swedish krona', }, { name: 'Switzerland', capital: 'Bern', languages: ['German', 'French', 'Italian'], population: 8341600, flag: 'https://restcountries.eu/data/che.svg', currency: 'Swiss franc', }, { name: 'Syrian Arab Republic', capital: 'Damascus', languages: ['Arabic'], population: 18564000, flag: 'https://restcountries.eu/data/syr.svg', currency: 'Syrian pound', }, { name: 'Taiwan', capital: 'Taipei', languages: ['Chinese'], population: 23503349, flag: 'https://restcountries.eu/data/twn.svg', currency: 'New Taiwan dollar', }, { name: 'Tajikistan', capital: 'Dushanbe', languages: ['Tajik', 'Russian'], population: 8593600, flag: 'https://restcountries.eu/data/tjk.svg', currency: 'Tajikistani somoni', }, { name: 'Tanzania, United Republic of', capital: 'Dodoma', languages: ['Swahili', 'English'], population: 55155000, flag: 'https://restcountries.eu/data/tza.svg', currency: 'Tanzanian shilling', }, { name: 'Thailand', capital: 'Bangkok', languages: ['Thai'], population: 65327652, flag: 'https://restcountries.eu/data/tha.svg', currency: 'Thai baht', }, { name: 'Timor-Leste', capital: 'Dili', languages: ['Portuguese'], population: 1167242, flag: 'https://restcountries.eu/data/tls.svg', currency: 'United States dollar', }, { name: 'Togo', capital: 'Lomé', languages: ['French'], population: 7143000, flag: 'https://restcountries.eu/data/tgo.svg', currency: 'West African CFA franc', }, { name: 'Tokelau', capital: 'Fakaofo', languages: ['English'], population: 1411, flag: 'https://restcountries.eu/data/tkl.svg', currency: 'New Zealand dollar', }, { name: 'Tonga', capital: "Nuku'alofa", languages: ['English', 'Tonga (Tonga Islands)'], population: 103252, flag: 'https://restcountries.eu/data/ton.svg', currency: 'Tongan paʻanga', }, { name: 'Trinidad and Tobago', capital: 'Port of Spain', languages: ['English'], population: 1349667, flag: 'https://restcountries.eu/data/tto.svg', currency: 'Trinidad and Tobago dollar', }, { name: 'Tunisia', capital: 'Tunis', languages: ['Arabic'], population: 11154400, flag: 'https://restcountries.eu/data/tun.svg', currency: 'Tunisian dinar', }, { name: 'Turkey', capital: 'Ankara', languages: ['Turkish'], population: 78741053, flag: 'https://restcountries.eu/data/tur.svg', currency: 'Turkish lira', }, { name: 'Turkmenistan', capital: 'Ashgabat', languages: ['Turkmen', 'Russian'], population: 4751120, flag: 'https://restcountries.eu/data/tkm.svg', currency: 'Turkmenistan manat', }, { name: 'Turks and Caicos Islands', capital: 'Cockburn Town', languages: ['English'], population: 31458, flag: 'https://restcountries.eu/data/tca.svg', currency: 'United States dollar', }, { name: 'Tuvalu', capital: 'Funafuti', languages: ['English'], population: 10640, flag: 'https://restcountries.eu/data/tuv.svg', currency: 'Australian dollar', }, { name: 'Uganda', capital: 'Kampala', languages: ['English', 'Swahili'], population: 33860700, flag: 'https://restcountries.eu/data/uga.svg', currency: 'Ugandan shilling', }, { name: 'Ukraine', capital: 'Kiev', languages: ['Ukrainian'], population: 42692393, flag: 'https://restcountries.eu/data/ukr.svg', currency: 'Ukrainian hryvnia', }, { name: 'United Arab Emirates', capital: 'Abu Dhabi', languages: ['Arabic'], population: 9856000, flag: 'https://restcountries.eu/data/are.svg', currency: 'United Arab Emirates dirham', }, { name: 'United Kingdom of Great Britain and Northern Ireland', capital: 'London', languages: ['English'], population: 65110000, flag: 'https://restcountries.eu/data/gbr.svg', currency: 'British pound', }, { name: 'United States of America', capital: 'Washington, D.C.', languages: ['English'], population: 323947000, flag: 'https://restcountries.eu/data/usa.svg', currency: 'United States dollar', }, { name: 'Uruguay', capital: 'Montevideo', languages: ['Spanish'], population: 3480222, flag: 'https://restcountries.eu/data/ury.svg', currency: 'Uruguayan peso', }, { name: 'Uzbekistan', capital: 'Tashkent', languages: ['Uzbek', 'Russian'], population: 31576400, flag: 'https://restcountries.eu/data/uzb.svg', currency: "Uzbekistani so'm", }, { name: 'Vanuatu', capital: 'Port Vila', languages: ['Bislama', 'English', 'French'], population: 277500, flag: 'https://restcountries.eu/data/vut.svg', currency: 'Vanuatu vatu', }, { name: 'Venezuela (Bolivarian Republic of)', capital: 'Caracas', languages: ['Spanish'], population: 31028700, flag: 'https://restcountries.eu/data/ven.svg', currency: 'Venezuelan bolívar', }, { name: 'Viet Nam', capital: 'Hanoi', languages: ['Vietnamese'], population: 92700000, flag: 'https://restcountries.eu/data/vnm.svg', currency: 'Vietnamese đồng', }, { name: 'Wallis and Futuna', capital: 'Mata-Utu', languages: ['French'], population: 11750, flag: 'https://restcountries.eu/data/wlf.svg', currency: 'CFP franc', }, { name: 'Western Sahara', capital: 'El Aaiún', languages: ['Spanish'], population: 510713, flag: 'https://restcountries.eu/data/esh.svg', currency: 'Moroccan dirham', }, { name: 'Yemen', capital: "Sana'a", languages: ['Arabic'], population: 27478000, flag: 'https://restcountries.eu/data/yem.svg', currency: 'Yemeni rial', }, { name: 'Zambia', capital: 'Lusaka', languages: ['English'], population: 15933883, flag: 'https://restcountries.eu/data/zmb.svg', currency: 'Zambian kwacha', }, { name: 'Zimbabwe', capital: 'Harare', languages: ['English', 'Shona', 'Northern Ndebele'], population: 14240168, flag: 'https://restcountries.eu/data/zwe.svg', currency: 'Botswana pula', }, ] ================================================ FILE: 11_Day_Events/11_events_boilerplate/src/data/ten_most_highest_populations.js ================================================ export const tenHighestPopulation = [ { country: 'World', population: 7693165599 }, { country: 'China', population: 1377422166 }, { country: 'India', population: 1295210000 }, { country: 'United States of America', population: 323947000 }, { country: 'Indonesia', population: 258705000 }, { country: 'Brazil', population: 206135893 }, { country: 'Pakistan', population: 194125062 }, { country: 'Nigeria', population: 186988000 }, { country: 'Bangladesh', population: 161006790 }, { country: 'Russian Federation', population: 146599183 }, { country: 'Japan', population: 126960000 }, ] ================================================ FILE: 11_Day_Events/11_events_boilerplate/src/index.js ================================================ // index.js import React, { Component } from 'react' import ReactDOM from 'react-dom' class App extends Component { state = { firstName: '', message: '', key: '', } handleClick = (e) => { // e gives an event object // check the value of e using console.log(e) this.setState({ message: 'Welcome to the world of events', }) } // triggered whenever the mouse moves handleMouseMove = (e) => { this.setState({ message: 'mouse is moving' }) } // to get value when an input field changes a value handleChange = (e) => { this.setState({ firstName: e.target.value, message: e.target.value, }) } // to get keyboard key code when an input field is pressed // it works with input and textarea handleKeyPress = (e) => { this.setState({ message: `${e.target.value} has been pressed and the keycode is` + e.charCode, }) } // Blurring happens when a mouse leave an input field handleBlur = (e) => { this.setState({ message: 'Input field has been blurred' }) } // This event triggers during a text copy handleCopy = (e) => { this.setState({ message: 'Using 30 Days Of React for commercial purpose is not allowed', }) } render() { return (

    Welcome to the World of Events

    Check copy right permission by copying this text

    {this.state.message}


    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ================================================ FILE: 12_Day_Forms/12_forms.md ================================================

    30 Days Of React: Forms

    Twitter Follow Author: Asabeneh Yetayeh
    October, 2020
    [<< Day 11](../11_Day_Events/11_events.md) | [Day 13 >>](../13_Day_Controlled_Versus_Uncontrolled_Input/13_uncontrolled_input.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_12.jpg) - [Forms](#forms) - [Getting data from an input field](#getting-data-from-an-input-field) - [Getting multiple input data from form](#getting-multiple-input-data-from-form) - [Get data from different input field types](#get-data-from-different-input-field-types) - [Form Validation](#form-validation) - [What is validation?](#what-is-validation) - [What is the purpose of validation](#what-is-the-purpose-of-validation) - [Validation Types](#validation-types) - [Exercises](#exercises) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 3](#exercises-level-3) # Forms Form is used to collect data from a user. Once in a while we use form to fill our information on a paper or on a website. Either to sign up, sign in or to apply for a job we fill different form fields to submit our data to remote database. We encounter different form fields when we fill a form such as simple text, email, password, telephone, date, checkbox, radio button, option selection and text area field. Currently, HTML5 has provide quite a lot of field types. You may have a look at the following available HTML5 input types. ```html ``` Another HTML fields to get data from a form are textarea and select with options elements. ```html ``` Now, you know most of the fields we need to get data from a form. Let's start with an input with type text field. In the previous day, we saw different types of events and today we will focus on more of _onChange_ event type which triggers whenever an input field data changes. Input field has by default a memory to store input data but in this section we control that using state and we implement a controlled input. Today we will implement a controlled input. We will cover uncontrolled input in a separate section. ## Getting data from an input field So far we did not get any data from input field. Now, it is time to learn how to get data from an input field. We need an input field, event listener (onChange) and state to get data from a controlled input. See the example below. The h1 element below the input tag display what we write on the input. Check live [demo](https://codepen.io/Asabeneh/full/OJVpyqm). The input element has many attributes such as value, name, id, placeholder, type and event handler. In addition, we can link a label and an input field using an id of input field and htmlFor of the label.If label and input are linked it will focus the input when we click on label. Look at the example give below. ```js import React, { Component } from 'react' import ReactDOM from 'react-dom' class App extends Component { // declaring state // initial state state = { firstName: '', } handleChange = (e) => { const value = e.target.value this.setState({ firstName: value }) } render() { /* accessing the state value and this value will injected to the input in the value attribute */ const firstName = this.state.firstName return (

    {this.state.firstName}

    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` We usually use form to handle user information. Let us move to form section and make use the form element. ## Getting multiple input data from form In this section we will develop a small form which collect user information. Our user is a student. We use a parent form element and certain number of input elements to collect user information. In addition to that we will have event listener for the form (onSubmit) and for the inputs (onChange). See the following example try to see the commonts too. You can also check the live [demo](https://codepen.io/Asabeneh/full/eYNvJda). ```js import React, { Component } from 'react' import ReactDOM from 'react-dom' class App extends Component { // declaring initial state state = { firstName: '', lastName: '', country: '', title: '', } handleChange = (e) => { /* we can get the name and value like this: e.target.name, e.target.value but we can also destructure name and value from e.target const name = e.target.name const value = e.target.value */ const { name, value } = e.target // [variablename] to use a variable name as a key in an object // name refers to the name attribute of the input elements this.setState({ [name]: value }) } handleSubmit = (e) => { /* e.preventDefault() stops the default behavior of form element specifically refreshing of page */ e.preventDefault() /* the is the place where we connect backend api to send the data to the database */ console.log(this.state) } render() { // accessing the state value by destrutcturing the state const { firstName, lastName, title, country } = this.state return (

    Add Student

    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` The above form handles only text types but do have different input field types. Let's do another form which handle all the different input field types. ## Get data from different input field types ```js // index.js import React, { Component } from 'react' import ReactDOM from 'react-dom' const options = [ { value: '', label: '-- Select Country--', }, { value: 'Finland', label: 'Finland', }, { value: 'Sweden', label: 'Sweden', }, { value: 'Norway', label: 'Norway', }, { value: 'Denmark', label: 'Denmark', }, ] // mapping the options to list(array) of JSX options const selectOptions = options.map(({ value, label }) => ( )) class App extends React.Component { // declaring state state = { firstName: '', lastName: '', email: '', country: '', tel: '', dateOfBirth: '', favoriteColor: '', weight: '', gender: '', file: '', bio: '', skills: { html: false, css: false, javascript: false, }, } handleChange = (e) => { /* we can get the name and value like: e.target.name, e.target.value Wwe can also destructure name and value from e.target const name = e.target.name const value = e.target.value */ const { name, value, type, checked } = e.target /* [variablename] we can make a value stored in a certain variable could be a key for an object, in this case a key for the state */ if (type === 'checkbox') { this.setState({ skills: { ...this.state.skills, [name]: checked }, }) } else if (type === 'file') { console.log(type, 'cehck here') this.setState({ [name]: e.target.files[0] }) } else { this.setState({ [name]: value }) } } handleSubmit = (e) => { /* e.preventDefault() stops the default behavior of form element specifically refreshing of page */ e.preventDefault() const { firstName, lastName, email, tel, dateOfBirth, favoriteColor, weight, country, gender, bio, file, skills, } = this.state const formattedSkills = [] for (const key in skills) { console.log(key) if (skills[key]) { formattedSkills.push(key.toUpperCase()) } } const data = { firstName, lastName, email, tel, dateOfBirth, favoriteColor, weight, country, gender, bio, file, skills: formattedSkills, } /* the is the place where we connect backend api to send the data to the database */ console.log(data) } render() { // accessing the state value by destrutcturing the state const { firstName, lastName, email, tel, dateOfBirth, favoriteColor, weight, country, gender, bio, } = this.state return (

    Add Student


    Gender

    Select your skills


    ``` Now, you know most of the fields we need to get data from a form. Let's start with an input with type text field. In the previous lessons, we saw different types of events and today we will focus on more of _onChange_ event type which triggers whenever an input field data changes. Input field has by default a memory to store input data but in this section we control that using state and we implement a controlled input. Today we will implement a controlled input. ## Getting data from an input field So far used class based components to use state and to get data from controlled input but in this section we will use useState hooks. Now, it is time to learn how to get data from an input field using hooks. We need an input field, event listener (onChange) and state to get data from a controlled input. See the example below. The h1 element below the input tag display what we write on the input. Check live [demo](https://codepen.io/Asabeneh/full/jOrVqbv). The input element has many attributes such as value, name, id, placeholder, type and event handler. In addition, we can link a label and an input field using an id of input field and htmlFor of the label.If label and input are linked it will focus the input when we click on label. Look at the example give below. ```js import React, { useState } from 'react' import ReactDOM from 'react-dom' const App = (props) => { // initial state and method to update state const [firstName, setFirstName] = useState('') const handleChange = (e) => { const value = e.target.value setFirstName(value) } return (

    {firstName}

    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` We usually use form to handle user information. Let us move to form section and make use the form element. ## Getting multiple input data from form In this section we will develop a small form which collect user information. Our user is a student. We use a parent form element and certain number of input elements to collect user information. In addition to that we will have event listener for the form (onSubmit) and for the inputs (onChange). See the following example try to see the commonts too. You can also check the live [demo](https://codepen.io/Asabeneh/full/eYNvJda). As you can see we have four fields, if you we create a separate method to update all the fields we will have method for updating(firstName, lastName, country and title) instead let's have one method which can update all. ```js import React, { useState } from 'react' import ReactDOM from 'react-dom' const App = (props) => { const initialState = { firstName: '', lastName: '', country: '', title: '', } const [formData, setData] = useState(initialState) const onChange = (e) => { const { name, value } = e.target setData({ ...formData, [name]: value }) } const onSubmit = (e) => { /* e.preventDefault() stops the default behavior of form element specifically refreshing of page */ e.preventDefault() /* the is the place where we connect backend api to send the data to the database */ console.log(formData) } // accessing the state value by destrutcturing the state const { firstName, lastName, title, country } = formData return (

    Add Student

    ) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` The above form handles only text types but do have different input field types. Let's do another form which handle all the different input field types. ## Get data from different input field types ```js // index.js import React, { useState } from 'react' import ReactDOM from 'react-dom' const options = [ { value: '', label: '-- Select Country--', }, { value: 'Finland', label: 'Finland', }, { value: 'Sweden', label: 'Sweden', }, { value: 'Norway', label: 'Norway', }, { value: 'Denmark', label: 'Denmark', }, ] // mapping the options to list(array) of JSX options const selectOptions = options.map(({ value, label }) => ( )) const App = (props) => { const initialState = { firstName: '', lastName: '', email: '', title: '', country: '', tel: '', dateOfBirth: '', favoriteColor: '', weight: '', gender: '', file: '', bio: '', skills: { html: false, css: false, javascript: false, }, } const [formData, setFormData] = useState(initialState) const onChange = (e) => { /* we can get the name and value like: e.target.name, e.target.value Wwe can also destructure name and value from e.target const name = e.target.name const value = e.target.value */ const { name, value, type, checked } = e.target /* [variablename] we can make a value stored in a certain variable could be a key for an object, in this case a key for the state */ if (type === 'checkbox') { setFormData({ ...formData, skills: { ...formData.skills, [name]: checked }, }) } else if (type === 'file') { setFormData({ ...formData, [name]: e.target.files[0] }) } else { setFormData({ ...formData, [name]: value }) } } const onSubmit = (e) => { /* e.preventDefault() stops the default behavior of form element specifically refreshing of page */ e.preventDefault() const { firstName, lastName, title, email, tel, dateOfBirth, favoriteColor, weight, country, gender, bio, file, skills, } = formData const formattedSkills = [] for (const key in skills) { console.log(key) if (skills[key]) { formattedSkills.push(key.toUpperCase()) } } const data = { firstName, lastName, title, email, tel, dateOfBirth, favoriteColor, weight, country, gender, bio, file, skills: formattedSkills, } /* the is the place where we connect backend api to send the data to the database */ console.log(data) } // accessing the state value by destrutcturing the state const { firstName, lastName, title, country, email, tel, dateOfBirth, favoriteColor, weight, gender, bio, } = formData return (

    Add Student


    Gender

    Select your skills