Merge remote-tracking branch 'upstream/master' into exercise-solutions

pull/73/head
Derrek Gass 5 years ago
commit f69d208dda

4
.gitignore vendored

@ -1,6 +1,6 @@
draft.md draft.md
react-for-everyone.md react-for-everyone.md
component.md component.md
10_Day_Events 14_Day_Component_Life_Cycles
11_Day_Forms

@ -1886,9 +1886,9 @@ person.isMarried = true
person.getPersonInfo = function () { person.getPersonInfo = function () {
let skillsWithoutLastSkill = this.skills let skillsWithoutLastSkill = this.skills
.splice(0, this.skills.length - 1) .slice(0, this.skills.length - 1)
.join(', ') .join(', ')
let lastSkill = this.skills.splice(this.skills.length - 1)[0] let lastSkill = this.skills.slice(this.skills.length - 1)[0]
let skills = `${skillsWithoutLastSkill}, and ${lastSkill}` let skills = `${skillsWithoutLastSkill}, and ${lastSkill}`
let fullName = this.getFullName() let fullName = this.getFullName()

@ -15,7 +15,7 @@
</div> </div>
</div> </div>
[<< Day 2](../02_Day_Introduction_to_React/02_introduction_to_react.md) | [Day 4 >>](./04_Day_Component/04_components.md) [<< 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) ![30 Days of React banner](../images/30_days_of_react_banner_day_3.jpg)
@ -36,6 +36,7 @@
- [Exercises](#exercises) - [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Setting Up # Setting Up
@ -747,21 +748,23 @@ The boilerplate code can be found [here](../03/../03_Day_Setting_Up/30-days-of-r
6. How do you create a new React project? 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)? 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)? 8. What is your favorite code editor (I believe that it is Visual Studio Code)?
9. Add different Visual Studio Code extensions to imporve your productivity(eg. prettier, ESLint etc). 9. Add different Visual Studio Code extensions to improve your productivity(eg. prettier, ESLint etc).
10. Try to make a different module in a different file and import it to index.js. 10. Try to make a different custom module in a different file and import it to index.js.
## Exercises: Level 2 ## Exercises: Level 2
1. Import and render the following images 1. Import and render the following images
![Front end](../images/frontend_technologies.png) ![Front end](../images/frontend_technologies.png)
2. Design the following user card. 2. Use h1, p, input and button HTML elements to create the following design using JSX
![User Card](../images/user_card_design_jsx.png) ![News Letter](../images/news_letter_design.png)
3. Use h1, p, input and button HTML elements to create the following design using JSX ## Exercises: Level 3
![News Letter](../images/news_letter_design.png) 1. Design the following user card.
![User Card](../images/user_card_design_jsx.png)
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉

@ -14,7 +14,7 @@
</div> </div>
[<< Day 3](../30-Days-Of-React/03_Day_Setting_Up/03_setting_up.md) | [Day 5 >>](./05_Day_Props/05_props.md) [<< 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) ![30 Days of React banner](../images/30_days_of_react_banner_day_4.jpg)
@ -28,37 +28,37 @@
- [Injecting data to JSX in React Component](#injecting-data-to-jsx-in-react-component) - [Injecting data to JSX in React Component](#injecting-data-to-jsx-in-react-component)
- [Further on Functional components](#further-on-functional-components) - [Further on Functional components](#further-on-functional-components)
- [Exercises: Components](#exercises-components) - [Exercises: Components](#exercises-components)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Components # Components
A React component is 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 a JavaScript function or class to make components. If we use a function the component will be a functional component but if we use class the function will be a class based component. 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: Components can be:
- Functional Component / Presentational Component / stateless component / Dumb components - Functional Component / Presentational Component / Stateless Component / Dumb Component
- Class Component / Container Component/ State full component / smart components - Class Component / Container Component/ Statefull Component / Smart Component
The above classifications of components does not work for the latest version of react but it is good to know the former definition and how the previous versions work. 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 class which return a JSX. Component name must start with an uppercase and if the name is two word should be CamelCase, camel with two humps. 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 ## Big picture of components
In the previous section, we agree 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 creating all over again whenever we need a button the same goes for input fields, forms, header or footer. That is where the power of component comes. In the following diagram, the header, main and footer are components. Inside the main also there is a user card component and a text section component. All the different colors represent different components. How many colors do you see? We have five components in this diagram. 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) ![Components](../images/components_example.png)
Before we jump into React components let's do some functions and class refreshers. Before we jump into React components, let's do some functions and class refreshers.
## JavaScript function ## JavaScript function
A JavaScript function could be either a regular function or an arrow function. There is a slight difference between an regular function and an arrow functions. 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 ```js
const getUserInfo = (firstName, lastName, country, title, skills) => { const getUserInfo = (firstName, lastName, country, title, skills) => {
return `${firstName} ${lastName}, a ${title} developer base in ${country}. He knows ${skills.join( return `${firstName} ${lastName}, a ${title} developer based in ${country}. He knows ${skills.join(
' ' ' '
)} ` )} `
} }
@ -71,7 +71,7 @@ console.log(
## JavaScript Class ## JavaScript Class
Class is a blue print 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. 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 ```js
class Parent { class Parent {
@ -118,13 +118,13 @@ const child = new Child(
) )
``` ```
We covered function and class in brief and React component is made from JavaScript functions or class. Now, lets make React component. 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 ## Creating React Component
### Functional Component ### Functional Component
Using a JavaScript function we can make a functional React component. Using a JavaScript function, we can make a functional React component.
```js ```js
// React component syntax // React component syntax
@ -189,7 +189,7 @@ const Header = () => (
### Rendering components ### 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 <ComponentName />. If we pass an attribute when we call the component name, we call it props(<ComponentName propsName = {'data type'} />). We will talk about props in its section.[Live on code pen](https://codepen.io/Asabeneh/full/wvaKKEM) 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 <ComponentName />. If we pass an attribute, when we call the component name, we call it props(<ComponentName propsName = {'data-type'} />). 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. Let's render first the _Header_ component.
@ -216,7 +216,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<Header />, rootElement) ReactDOM.render(<Header />, rootElement)
``` ```
Now, let's create an App component which hold the Header, Main and Footer. Then the App component will be render on the DOM. 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 ```js
// index.js // index.js
@ -292,9 +292,9 @@ ReactDOM.render(<App />, rootElement)
### Injecting data to JSX in React Component ### 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 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. 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 only inject only strings In this section we inject only strings
```js ```js
import React from 'react' import React from 'react'
@ -438,15 +438,14 @@ ReactDOM.render(<App />, rootElement)
### Further on Functional components ### 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 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.
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 ```js
const Button = () => <button>action</button> const Button = () => <button>action</button>
``` ```
The _Button_ component is made of a single HTML button element. 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 number without unit as CSS value is considered as px. See the example below. 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 ```js
const buttonStyles = { const buttonStyles = {
@ -458,7 +457,7 @@ const buttonStyles = {
const Button = () => <button style={buttonStyles}> action </button> const Button = () => <button style={buttonStyles}> action </button>
``` ```
The Button component is a dumb component because it does not take any parameter and we can not change the action text dynamically. We need to pass a 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. 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 ```js
import React from 'react' import React from 'react'
@ -484,34 +483,35 @@ ReactDOM.render(<HexaColor />, rootElement)
# Exercises: Components # Exercises: Components
## Exercises: Level 1 1. What is the difference between a regular function and an arrow function?
2. What is a React Component?
1. What is a React Component ? 3. How do you make a React functional component?
2. How do you make a React functional component ? 4. What is the difference between a pure JavaScript function and a functional component?
3. What is the difference between a pure JavaScript function and a functional component ? 5. How small is a React component?
4. How small is a React component ? 6. Can we make a button or input field component?
5. Can we make a button or input field component ? 7. Make a reusable Button component.
6. Make a reusable Button component 8. Make a reusable InputField component.
7. 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).
8. 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 ## Exercises: Level 2
1. Create functional components and display the following images 1. Create functional components and display the following images
![Front end](../images/frontend_technologies.png) ![Front end](../images/frontend_technologies.png)
2.Use functional component to design the following user card. 2. Use functional component to create the following design
![User Card](../images/user_card_design_jsx.png)
3. Use functional component to create the following design
![News Letter](../images/news_letter_design.png) ![News Letter](../images/news_letter_design.png)
4. Use the given hexadecimal color generator in the example to create these random colors ## 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) ![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 ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 3](../30-Days-Of-React/03_Day_Setting_Up/03_setting_up.md) | [Day 5 >>](./05_Day_Props/05_props.md) [<< Day 3](../30-Days-Of-React/03_Day_Setting_Up/03_setting_up.md) | [Day 5 >>](../05_Day_Props/05_props.md)

@ -1,4 +1,4 @@
# 30 Days of React App: Day 3 # 30 Days of React App: Day 4
In the project directory, you can run to start the project In the project directory, you can run to start the project

@ -12,7 +12,6 @@
<small> October, 2020</small> <small> October, 2020</small>
</sub> </sub>
</div>
</div> </div>
[<< Day 4](../04_Day_Component/04_components.md) | [Day 6 >>](../06_Day_Map_List_Keys/06_map_list_keys.md) [<< Day 4](../04_Day_Component/04_components.md) | [Day 6 >>](../06_Day_Map_List_Keys/06_map_list_keys.md)
@ -36,6 +35,7 @@
- [Exercises: Components and Props](#exercises-components-and-props) - [Exercises: Components and Props](#exercises-components-and-props)
- [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Props # Props
@ -47,7 +47,7 @@ In the previous day, we saw how to inject different data types to React componen
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. 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 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. 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 ```js
// function syntax // function syntax
@ -78,7 +78,7 @@ const User = (props) => {
<User firstName = 'Asabeneh', lastName='Yetayeh' country = 'Finland' /> <User firstName = 'Asabeneh', lastName='Yetayeh' country = 'Finland' />
``` ```
In the previous section, we injected data as follow and today we will change these data to a props. In the previous section, we injected data as follows and today we will change these data to props.
```js ```js
const welcome = 'Welcome to 30 Days Of React' const welcome = 'Welcome to 30 Days Of React'
@ -106,7 +106,7 @@ const Header = () => (
) )
``` ```
Instead of injecting data we can also pass the data as a props. React props is similar to parameters in function. Instead of injecting data we can also pass the data as props. React props are similar to parameters in functions.
## Props object ## Props object
@ -163,7 +163,7 @@ const Header = (props) => {
return ( return (
<header> <header>
<div className='header-wrapper'> <div className='header-wrapper'>
<h1>{welcome}</h1> <h1>{props.welcome}</h1>
</div> </div>
</header> </header>
) )
@ -192,7 +192,7 @@ Now, when you do console.log(props) you should get the following object, that me
} }
``` ```
As you can see in the above code, we passed only a 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. 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 ### Different data type props
@ -372,7 +372,7 @@ ReactDOM.render(<App />, rootElement)
### Array props type ### Array props type
In programming arrays and objects are the most frequent use data structure to solve different problems and store data in more structured way. Therefore, we encounter data in the form of array quite often. Let's pass an array props to a component 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 ```js
import React from 'react' import React from 'react'
@ -390,7 +390,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, 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 skills. 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 back to day 1 JavaScript refresher. Let's apply map to modify the array. 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 ```js
import React from 'react' import React from 'react'
@ -413,12 +413,12 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
We will go in depth about list and map in an other sections. Now, let's see an object as a props. We will go in-depth about list and map in other sections. Now, let's see an object as a props.
### Object props type ### Object props type
We may pass an object as props to a React component. Let's see an example. 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 few properties for better understanding. We can change the previous Header props to object. For the time being let's change a few properties for better understanding.
```js ```js
import React from 'react' import React from 'react'
@ -457,7 +457,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
Now, let's change all the previous Header properties to an objects. Now, let's change all the previous Header properties to an object.
```js ```js
import React from 'react' import React from 'react'
@ -525,11 +525,11 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
When we use object as props we usually destructure the data to access the values. Destructuring makes our code easy to read. We will see soon destructuring of props but before that let's see function as a props for a React component. 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 ### Function prop types
We can pass function as prop type to a React component. Let's see examples We can pass a function as props type to a React component. Let's see some examples
```js ```js
import React from 'react' import React from 'react'
@ -557,7 +557,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
Even we can write function inside the curly bracket Even we can write a function inside the curly bracket
```js ```js
import React from 'react' import React from 'react'
@ -581,7 +581,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
Now, lets implement different functions as a props Now, lets implement different functions as props
```js ```js
import React from 'react' import React from 'react'
@ -609,9 +609,9 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
In the above example, onClick is a props to hold the greetPeople functions. 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. 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 another more function as props to give a clear understanding how to handle function as a props in React component. 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. This component shows month, date and year as an alert box.
@ -668,7 +668,7 @@ ReactDOM.render(<App />, rootElement)
## Destructuring props ## Destructuring props
By now, I believe you are a JavaScript ninja and you know about destructing arrays and object. Destructuring code to some extent makes easy to read. Let us destructure the props in Header component. Everything we passed as a 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: 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 1. Step by step destructuring
@ -1057,41 +1057,43 @@ ReactDOM.render(<App />, rootElement)
## propTypes ## propTypes
The propTypes package help as to assign the data types of the props we passed to a component. The propTypes package helps us to assign the data types of the props we passed to a component.
## defaultProps ## defaultProps
The defaultProps can be used when we want to have some default prop types for a component. 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 section. We will cover propTypes in detail in other sections.
# Exercises: Components and Props # Exercises: Components and Props
## Exercises: Level 1 ## Exercises: Level 1
1. What is props in a React component ? 1. What is props in a React component ?
2. How do you access props in React component ? 2. How do you access props in a React component ?
3. What data types can we pass as a props to components ? 3. What data types can we pass as props to components ?
4. What is a propTypes 4. What is a propTypes?
5. What is a default propTypes 5. What is a default propTypes?
## Exercises: Level 2 ## Exercises: Level 2
1. Create functional components and display the following images 1. Create a functional component and display the following images
![Front end](../images/frontend_technologies.png) ![Front end](../images/frontend_technologies.png)
2.Use functional component to design the following user card. 2. Use functional component to create the following design
![User Card](../images/user_card_design_jsx.png)
3. Use functional component to create the following design
![News Letter](../images/news_letter_design.png) ![News Letter](../images/news_letter_design.png)
4. Use the given hexadecimal color generator in the example to create these random colors ## 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) ![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 ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 4](../04_Day_Component/04_components.md) | [Day 6 >>](../06_Day_Map_List_Keys/06_map_list_keys.md) [<< Day 4](../04_Day_Component/04_components.md) | [Day 6 >>](../06_Day_Map_List_Keys/06_map_list_keys.md)

@ -1,4 +1,4 @@
# 30 Days of React App: Day 3 # 30 Days of React App: Day 5
In the project directory, you can run to start the project In the project directory, you can run to start the project

@ -31,13 +31,13 @@
# Mapping arrays # Mapping arrays
Array is the most frequently used data structure to handle many kind 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 the array. 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 ## Mapping and rendering arrays
Most of the time data is in the form of array or 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 map. In this section also we will also see more examples. 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 a number array, a string array, a countries array and skills array on the browser. 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 ```js
import React from 'react' import React from 'react'
@ -57,7 +57,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, 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 JSX elements. 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 ### Mapping array of numbers
@ -183,7 +183,7 @@ ReactDOM.render(<App />, rootElement)
### Key in mapping arrays ### Key in mapping arrays
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Key should be unique. Mostly data has come with an id and we can use id as key. If we do not pass key react raise a warning on the browser. If the data does not have id we have to find a way to create a unique identifier for each elements when we map it. See the following example: 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 ```js
import React from 'react' import React from 'react'
@ -279,7 +279,7 @@ ReactDOM.render(<App />, rootElement)
## Exercises: Level 3 ## Exercises: Level 3
1.Make the following bar group using given [data](../06_Day_Map_List_Keys/06_map_list_keys_boilerplate/src/data/ten_most_highest_populations.js) 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) ![Ten most highest populations](../images/day_6_ten_highest_populations_exercise.png)

@ -1,4 +1,4 @@
# 30 Days of React App: Day 3 # 30 Days of React App: Day 6
In the project directory, you can run to start the project In the project directory, you can run to start the project

@ -1,4 +1,4 @@
# 30 Days of React App: Day 3 # 30 Days of React App: Day 7
In the project directory, you can run to start the project In the project directory, you can run to start the project

@ -14,7 +14,7 @@
</div> </div>
[<< Day 6](../06_Day_Map_List_Keys/06_map_list_keys.md) | [Day 8 >>](../07_Day_Class_Components/07_class_components.md) [<< 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) ![30 Days of React banner](../images/30_days_of_react_banner_day_7.jpg)
@ -24,10 +24,11 @@
- [Exercises](#exercises) - [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Class Components # Class Components
In the previous sections, we have covered JSX, functional component and props. In this section, we will cover class components or statefull 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. 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. 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.
@ -833,6 +834,10 @@ In next section, we will cover state which is the heart of React. State allows R
Learn more about class based component by changing previous days exercises to class based components Learn more about class based component by changing previous days exercises to class based components
## Exercises: Level 3
Coming ...
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 6](../06_Day_Map_List_Keys/06_map_list_keys.md) | [Day 8 >>](../07_Day_Class_Components/07_class_components.md) [<< Day 6](../06_Day_Map_List_Keys/06_map_list_keys.md) | [Day 8 >>](../08_Day_States/08_states.md)

@ -1,5 +1,5 @@
<div align="center"> <div align="center">
<h1> 30 Days Of React: Statet</h1> <h1> 30 Days Of React: States</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/"> <a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social"> <img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a> </a>
@ -18,7 +18,7 @@
![30 Days of React banner](../images/30_days_of_react_banner_day_8.jpg) ![30 Days of React banner](../images/30_days_of_react_banner_day_8.jpg)
- [State](#state) - [States](#states)
- [What is State?](#what-is-state) - [What is State?](#what-is-state)
- [How to set a state](#how-to-set-a-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) - [Resetting a state using a JavaScript method](#resetting-a-state-using-a-javascript-method)
@ -27,7 +27,7 @@
- [Exercises: Level 2](#exercises-level-2) - [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3) - [Exercises: Level 3](#exercises-level-3)
# State # States
## What is State? ## What is State?

@ -1,4 +1,4 @@
# 30 Days of React App: Day 3 # 30 Days of React App: Day 8
In the project directory, you can run to start the project In the project directory, you can run to start the project

@ -14,7 +14,7 @@
</div> </div>
[<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_Day_Events/10_events.md) [<< 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) ![30 Days of React banner](../images/30_days_of_react_banner_day_9.jpg)
@ -34,7 +34,6 @@ import ReactDOM from 'react-dom'
// class based component // class based component
class Header extends React.Component { class Header extends React.Component {
render() { render() {
console.log(this.props.data)
const { const {
welcome, welcome,
title, title,
@ -44,7 +43,7 @@ class Header extends React.Component {
} = this.props.data } = this.props.data
return ( return (
<header style={this.props.styles}> <header>
<div className='header-wrapper'> <div className='header-wrapper'>
<h1>{welcome}</h1> <h1>{welcome}</h1>
<h2>{title}</h2> <h2>{title}</h2>
@ -74,7 +73,7 @@ class App extends React.Component {
firstName: 'Asabeneh', firstName: 'Asabeneh',
lastName: 'Yetayeh', lastName: 'Yetayeh',
}, },
date: 'Oct 7, 2020', date: 'Oct 9, 2020',
} }
// conditional rendering using if and else statement // conditional rendering using if and else statement
@ -89,7 +88,6 @@ class App extends React.Component {
return ( return (
<div className='app'> <div className='app'>
{this.state.backgroundColor}
<Header data={data} /> <Header data={data} />
{status} {status}
</div> </div>
@ -121,11 +119,10 @@ const buttonStyles = {
padding: 10, padding: 10,
border: 'none', border: 'none',
borderRadius: 5, borderRadius: 5,
margin: 3, margin: '3px auto',
cursor: 'pointer', cursor: 'pointer',
fontSize: 22, fontSize: 22,
color: 'white', color: 'white',
margin: '0 auto',
} }
// class based component // class based component
@ -141,7 +138,7 @@ class Header extends React.Component {
} = this.props.data } = this.props.data
return ( return (
<header style={this.props.styles}> <header>
<div className='header-wrapper'> <div className='header-wrapper'>
<h1>{welcome}</h1> <h1>{welcome}</h1>
<h2>{title}</h2> <h2>{title}</h2>
@ -191,7 +188,6 @@ class App extends React.Component {
return ( return (
<div className='app'> <div className='app'>
{this.state.backgroundColor}
<Header data={data} /> <Header data={data} />
{status} {status}
<Button text={text} style={buttonStyles} onClick={this.handleLogin} /> <Button text={text} style={buttonStyles} onClick={this.handleLogin} />
@ -228,17 +224,15 @@ const buttonStyles = {
padding: 10, padding: 10,
border: 'none', border: 'none',
borderRadius: 5, borderRadius: 5,
margin: 3, margin: '3px auto',
cursor: 'pointer', cursor: 'pointer',
fontSize: 22, fontSize: 22,
color: 'white', color: 'white',
margin: '0 auto',
} }
// class based component // class based component
class Header extends React.Component { class Header extends React.Component {
render() { render() {
console.log(this.props.data)
const { const {
welcome, welcome,
title, title,
@ -248,7 +242,7 @@ class Header extends React.Component {
} = this.props.data } = this.props.data
return ( return (
<header style={this.props.styles}> <header>
<div className='header-wrapper'> <div className='header-wrapper'>
<h1>{welcome}</h1> <h1>{welcome}</h1>
<h2>{title}</h2> <h2>{title}</h2>
@ -293,7 +287,6 @@ class App extends React.Component {
return ( return (
<div className='app'> <div className='app'>
{this.state.backgroundColor}
<Header data={data} /> <Header data={data} />
{status} {status}
<Button <Button
@ -330,17 +323,15 @@ const buttonStyles = {
padding: 10, padding: 10,
border: 'none', border: 'none',
borderRadius: 5, borderRadius: 5,
margin: 3, margin: '3px auto',
cursor: 'pointer', cursor: 'pointer',
fontSize: 22, fontSize: 22,
color: 'white', color: 'white',
margin: '0 auto',
} }
// class based component // class based component
class Header extends React.Component { class Header extends React.Component {
render() { render() {
console.log(this.props.data)
const { const {
welcome, welcome,
title, title,
@ -350,7 +341,7 @@ class Header extends React.Component {
} = this.props.data } = this.props.data
return ( return (
<header style={this.props.styles}> <header>
<div className='header-wrapper'> <div className='header-wrapper'>
<h1>{welcome}</h1> <h1>{welcome}</h1>
<h2>{title}</h2> <h2>{title}</h2>
@ -365,6 +356,17 @@ class Header extends React.Component {
} }
} }
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div>
<h1>Welcome to 30 Days Of React</h1>
</div>
)
class App extends React.Component { class App extends React.Component {
state = { state = {
loggedIn: false, loggedIn: false,
@ -387,22 +389,10 @@ class App extends React.Component {
date: 'Oct 9, 2020', date: 'Oct 9, 2020',
} }
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div>
<h1>Welcome to 30 Days Of React</h1>
</div>
)
const status = this.state.loggedIn ? <Welcome /> : <Login /> const status = this.state.loggedIn ? <Welcome /> : <Login />
return ( return (
<div className='app'> <div className='app'>
{this.state.backgroundColor}
<Header data={data} /> <Header data={data} />
{status} {status}
<Button <Button
@ -441,11 +431,10 @@ const buttonStyles = {
padding: 10, padding: 10,
border: 'none', border: 'none',
borderRadius: 5, borderRadius: 5,
margin: 3, margin: '3px auto',
cursor: 'pointer', cursor: 'pointer',
fontSize: 22, fontSize: 22,
color: 'white', color: 'white',
margin: '0 auto',
} }
// class based component // class based component
@ -509,22 +498,25 @@ class App extends React.Component {
date: 'Oct 9, 2020', date: 'Oct 9, 2020',
} }
const status = this.state.loggedIn ? <Welcome /> : <Login /> // We can destructure state
const { loggedIn, techs } = this.state
const status = loggedIn ? <Welcome /> : <Login />
return ( return (
<div className='app'> <div className='app'>
{this.state.backgroundColor}
<Header data={data} /> <Header data={data} />
{status} {status}
<Button <Button
text={this.state.loggedIn ? 'Logout' : 'Login'} text={loggedIn ? 'Logout' : 'Login'}
style={buttonStyles} style={buttonStyles}
onClick={this.handleLogin} onClick={this.handleLogin}
/> />
{this.state.techs.length === 3 && ( {techs.length === 3 && (
<p>You have all the prerequisite courses to get started React</p> <p>You have all the prerequisite courses to get started React</p>
)} )}
{!this.state.loggedIn && ( {!loggedIn && (
<p> <p>
Please login to access more information about 30 Days Of React Please login to access more information about 30 Days Of React
challenge challenge
@ -667,11 +659,10 @@ const buttonStyles = {
padding: 10, padding: 10,
border: 'none', border: 'none',
borderRadius: 5, borderRadius: 5,
margin: 3, margin: '3px auto',
cursor: 'pointer', cursor: 'pointer',
fontSize: 22, fontSize: 22,
color: 'white', color: 'white',
margin: '0 auto',
} }
// Footer Component // Footer Component
@ -743,11 +734,9 @@ class App extends React.Component {
}, },
date: 'Oct 9, 2020', date: 'Oct 9, 2020',
} }
const techs = ['HTML', 'CSS', 'JavaScript']
return ( return (
<div className='app'> <div className='app'>
{this.state.backgroundColor}
<Header data={data} /> <Header data={data} />
<Main <Main
@ -779,7 +768,8 @@ ReactDOM.render(<App />, rootElement)
### Exercises: Level 2 ### Exercises: Level 2
Coming 1. Make a single page application which changes the body of the background based on the time of the day(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 ### Exercises: Level 3
@ -787,4 +777,4 @@ Coming
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_Day_Events/10_events.md) [<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_React_Project_Folder_Structure/10_react_project_folder_structure.md)

@ -1,4 +1,4 @@
# 30 Days of React App: Day 3 # 30 Days of React App: Day 9
In the project directory, you can run to start the project In the project directory, you can run to start the project

@ -5,7 +5,6 @@ import ReactDOM from 'react-dom'
// class based component // class based component
class Header extends React.Component { class Header extends React.Component {
render() { render() {
console.log(this.props.data)
const { const {
welcome, welcome,
title, title,
@ -15,7 +14,7 @@ class Header extends React.Component {
} = this.props.data } = this.props.data
return ( return (
<header style={this.props.styles}> <header>
<div className='header-wrapper'> <div className='header-wrapper'>
<h1>{welcome}</h1> <h1>{welcome}</h1>
<h2>{title}</h2> <h2>{title}</h2>
@ -128,11 +127,10 @@ const buttonStyles = {
padding: 10, padding: 10,
border: 'none', border: 'none',
borderRadius: 5, borderRadius: 5,
margin: 3, margin: '3px auto',
cursor: 'pointer', cursor: 'pointer',
fontSize: 22, fontSize: 22,
color: 'white', color: 'white',
margin: '0 auto',
} }
// Footer Component // Footer Component
@ -208,7 +206,6 @@ class App extends React.Component {
return ( return (
<div className='app'> <div className='app'>
{this.state.backgroundColor}
<Header data={data} /> <Header data={data} />
<Main <Main

@ -0,0 +1,623 @@
<div align="center">
<h1> 30 Days Of React: React Project Folder Structure</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> October, 2020</small>
</sub>
</div>
[<< 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 = () => <h1>Welcome to 30 Days Of React</h1>
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, 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 = () => <h1>Welcome to 30 Days Of React</h1>
```
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 = () => <h1>Welcome to 30 Days Of React</h1>
```
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 <h1>Welcome to 30 Days Of React</h1>
}
```
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(<App />, 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 = () => <h1>Welcome to 30 Days Of React</h1>
```
```js
// src/App.js
import React from 'react
// export default in arrow function
export default function App () {
return <h1>Welcome to 30 Days Of React</h1>
}
```
```js
// src/App.js
// Recommended for most of the cases
import React from 'react
const App = () => <h1>Welcome to 30 Days Of React</h1>
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(<App />, 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 (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
}
const Country = ({
country: { name, capital, flag, languages, population, currency },
}) => {
const formatedCapital =
capital.length > 0 ? (
<>
<span>Capital: </span>
{capital}
</>
) : (
''
)
const formatLanguage = languages.length > 1 ? `Languages` : `Language`
return (
<div className='country'>
<div className='country_flag'>
<img src={flag} alt={name} />
</div>
<h3 className='country_name'>{name.toUpperCase()}</h3>
<div class='country_text'>
<p>{formatedCapital}</p>
<p>
<span>{formatLanguage}: </span>
{languages.join(', ')}
</p>
<p>
<span>Population: </span>
{population.toLocaleString()}
</p>
<p>
<span>Currency: </span>
{currency}
</p>
</div>
</div>
)
}
// User Card Component
const UserCard = () => (
<div className='user-card'>
<img src={asabenehImage} alt='asabeneh image' />
<h2>Asabeneh Yetayeh</h2>
</div>
)
// 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 = () => <div>{hexaColor()}</div>
const Message = ({ message }) => (
<div>
<h1>{message}</h1>
</div>
)
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div>
<h1>Welcome to 30 Days Of React</h1>
</div>
)
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// TechList Component
// class base component
class TechList extends React.Component {
render() {
const { techs } = this.props
const techsFormatted = techs.map((tech) => <li key={tech}>{tech}</li>)
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 ? <Welcome /> : <Login />
return (
<main>
<div className='main-wrapper'>
<p>Prerequisite to get started react.js:</p>
<ul>
<TechList techs={this.props.techs} />
</ul>
{techs.length === 3 && (
<p>You have all the prerequisite courses to get started React</p>
)}
<div>
<Button
text='Show Time'
onClick={handleTime}
style={buttonStyles}
/>{' '}
<Button
text='Greet People'
onClick={greetPeople}
style={buttonStyles}
/>
{!loggedIn && <p>Please login to access more information about 30 Days Of React challenge</p>}
</div>
<div style={{ margin: 30 }}>
<Button
text={loggedIn ? 'Logout' : 'Login'}
style={buttonStyles}
onClick={handleLogin}
/>
<br />
{status}
</div>
<Message message={message} />
</div>
</main>
)
}
}
// 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 (
<footer>
<div className='footer-wrapper'>
<p>Copyright {this.props.date.getFullYear()}</p>
</div>
</footer>
)
}
}
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 (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
<Main
techs={techs}
handleTime={this.handleTime}
greetPeople={this.greetPeople}
loggedIn={this.state.loggedIn}
handleLogin={this.handleLogin}
message={this.state.message}
/>
<Footer date={new Date()} />
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, 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 (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
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 (
<Fragment>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</Fragment>
)
}
const RequiredSkills = () => {
return (
<ul>
<Skills />
</ul>
)
}
```
It is also possible to just extract the fragment module from React as shown below.
```js
import React from 'react'
const Skills = () => {
return (
<React.Fragment>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</React.Fragment>
)
}
const RequiredSkills = () => {
return (
<ul>
<Skills />
</ul>
)
}
```
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 (
<>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</>
)
}
const RequiredSkills = () => {
return (
<ul>
<Skills />
</ul>
)
}
```
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 <h1> 30 Days of React </h1>
}
}
```
```js
import React, { Component } from 'react'
// This is recommended
class App extends Component {
render() {
return <h1> 30 Days of React </h1>
}
}
```
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 we export file
3. How do we 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)

@ -0,0 +1,23 @@
# 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*

@ -0,0 +1,5 @@
# 30 Days of React App: Day 10
In the project directory, you can run to start the project
### `npm start`

@ -0,0 +1,34 @@
{
"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"
]
}
}

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500|Aldrich:300,400, 500|Oswald:300,400, 500|Raleway:300,400, 500|Roboto:300,400,500&display=swap"
rel="stylesheet"
/>
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>30 Days Of React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

@ -0,0 +1,65 @@
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 (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
<Main
techs={techs}
handleTime={this.handleTime}
greetPeople={this.greetPeople}
loggedIn={this.state.loggedIn}
handleLogin={this.handleLogin}
message={this.state.message}
country={this.state.country}
user={user}
/>
<Footer date={new Date()} />
</div>
)
}
}
export default App

@ -0,0 +1,13 @@
import React from 'react'
import { hexaColor } from '../../utils/hexadecimal-color-generator'
const HexaColor = (props) => {
return (
<div style={{ textAlign: 'center', border: '2px solid', height: 50 }}>
{hexaColor()}
</div>
)
}
HexaColor.propTypes = {}
export default HexaColor

@ -0,0 +1,40 @@
import React from 'react'
const Country = ({
country: { name, capital, flag, languages, population, currency },
}) => {
const formatedCapital =
capital.length > 0 ? (
<>
<span>Capital: </span>
{capital}
</>
) : (
''
)
const formatLanguage = languages.length > 1 ? `Languages` : `Language`
return (
<div className='country'>
<div className='country_flag'>
<img src={flag} alt={name} />
</div>
<h3 className='country_name'>{name.toUpperCase()}</h3>
<div class='country_text'>
<p>{formatedCapital}</p>
<p>
<span>{formatLanguage}: </span>
{languages.join(', ')}
</p>
<p>
<span>Population: </span>
{population.toLocaleString()}
</p>
<p>
<span>Currency: </span>
{currency}
</p>
</div>
</div>
)
}
export default Country

@ -0,0 +1,11 @@
import React from 'react'
const Footer = ({ date }) => {
return (
<footer>
<div className='footer-wrapper'>
<p>Copyright {date.getFullYear()}</p>
</div>
</footer>
)
}
export default Footer

@ -0,0 +1,29 @@
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 (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{showDate(date)}</small>
</div>
</header>
)
}
export default Header

@ -0,0 +1,108 @@
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) => <li key={tech}>{tech}</li>)
return techsFormatted
}
}
const Message = ({ message }) => (
<div
style={{
border: '2px solid #61dbfb',
margin: 25,
padding: 10,
}}
>
<h3>{message}</h3>
</div>
)
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div style={{ border: '2px solid rgb(0,255,0', margin: 10, padding: 10 }}>
<h2>Welcome to 30 Days Of React</h2>
</div>
)
// 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 ? <Welcome /> : <Login />
return (
<main>
<div className='main-wrapper'>
<p>Prerequisite to get started react.js:</p>
<ul>
<TechList techs={this.props.techs} />
</ul>
<UserCard user={user} />
{techs.length === 3 && (
<p>You have all the prerequisite courses to get started React</p>
)}
<div>
<Button
text='Show Time'
onClick={handleTime}
style={buttonStyles}
/>{' '}
<Button
text='Greet People'
onClick={greetPeople}
style={buttonStyles}
/>
{!loggedIn && (
<p>
Please login to access more information about 30 Days Of React
challenge
</p>
)}
</div>
<div style={{ margin: 30 }}>
<Button
text={loggedIn ? 'Logout' : 'Login'}
style={buttonStyles}
onClick={handleLogin}
/>
<br />
{status}
</div>
<Message message={message} />
<HexaColr />
<HexaColr />
<Country country={country} />
</div>
</main>
)
}
}
export default Main

@ -0,0 +1,11 @@
import React from 'react'
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
export default Button

@ -0,0 +1,15 @@
import React from 'react'
// User Card Component
const UserCard = ({ user: { firstName, lastName, image } }) => (
<div className='user-card'>
<img src={image} alt='asabeneh image' />
<h2>
{firstName}
{lastName}
</h2>
</div>
)
export default UserCard

@ -0,0 +1,13 @@
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 },
]

@ -0,0 +1,10 @@
// 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(<App />, rootElement)

@ -0,0 +1,12 @@
// 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',
}

@ -0,0 +1,57 @@
* {
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;
}

@ -0,0 +1,60 @@
/* 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;
}

@ -0,0 +1,14 @@
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;
}

@ -0,0 +1,5 @@
header {
background-color: #61dbfb;
padding: 25;
padding: 10px;
}

@ -0,0 +1,8 @@
/* == 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';

@ -0,0 +1,7 @@
.user-card {
margin-top: 10px;
}
.user-card > img {
border-radius: 50%;
width: 14%;
}

@ -0,0 +1,21 @@
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}`
}

@ -0,0 +1,10 @@
// 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
}

@ -0,0 +1,239 @@
<div align="center">
<h1> 30 Days Of React: Events</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> October, 2020</small>
</sub>
</div>
[<< 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>30 Days Of React App</title>
</head>
<body>
<button>onclick="greetPeople()">Greet People</button>
<script>
const greetPeople = () => {
alert('Welcome to 30 Days Of React Challenge')
}
</script>
</body>
</html>
```
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 <button onClick={greetPeople}> </button>
}
```
```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 <button onClick={this.greetPeople}> </button>
}
}
```
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
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
```
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 (
<a href='#' onClick={this.handleClick}>
Click me
</a>
)
}
}
```
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 (
<div>
<h1>Welcome to the World of Events</h1>
<button onClick={this.handleClick}>Click Me</button>
<button onMouseMove={this.handleMouseMove}>Move mouse on me</button>
<p onCopy={this.handleCopy}>
Check copy right permission by copying this text
</p>
<p>{this.state.message}</p>
<label htmlFor=''> Test for onKeyPress Event: </label>
<input type='text' onKeyPress={this.handleKeyPress} />
<br />
<label htmlFor=''> Test for onBlur Event: </label>
<input type='text' onBlur={this.handleBlur} />
<form onSubmit={this.handleSubmit}>
<div>
<label htmlFor='firstName'>First Name: </label>
<input
onChange={this.handleChange}
name='firstName'
value={this.state.value}
/>
</div>
<div>
<input type='submit' value='Submit' />
</div>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
// we render the JSX element using the ReactDOM package
ReactDOM.render(<App />, 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)

@ -0,0 +1,23 @@
# 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*

@ -0,0 +1,5 @@
# 30 Days of React App: Day 11
In the project directory, you can run to start the project
### `npm start`

@ -0,0 +1,34 @@
{
"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"
]
}
}

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>30 Days Of React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,13 @@
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 },
]

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

@ -0,0 +1,87 @@
// 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 (
<div>
<h1>Welcome to the World of Events</h1>
<button onClick={this.handleClick}>Click Me</button>
<button onMouseMove={this.handleMouseMove}>Move mouse on me</button>
<p onCopy={this.handleCopy}>
Check copy right permission by copying this text
</p>
<p>{this.state.message}</p>
<label htmlFor=''> Test for onKeyPress Event: </label>
<input type='text' onKeyPress={this.handleKeyPress} />
<br />
<label htmlFor=''> Test for onBlur Event: </label>
<input type='text' onBlur={this.handleBlur} />
<form onSubmit={this.handleSubmit}>
<div>
<label htmlFor='firstName'>First Name: </label>
<input
onChange={this.handleChange}
name='firstName'
value={this.state.value}
/>
</div>
<div>
<input type='submit' value='Submit' />
</div>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,950 @@
<div align="center">
<h1> 30 Days Of React: Forms</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> October, 2020</small>
</sub>
</div>
[<< 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
<input type="text" />
<input type="number" />
<input type="range" />
<input type="email" />
<input type="password" />
<input type="tel" />
<input type="checkbox" />
<input type="radio" />
<input type="color" />
<input type="url" />
<input type="image" />
<input type="file" />
<input type="hidden" />
<input type="date" />
<input type="datetime-local" />
<input type="month" />
<input type="week" />
<input type="time" />
<input type="reset" />
<input type="search" />
<input type="submit" />
<input type="button" />
```
Another HTML fields to get data from a form are textarea and select with options elements.
```html
<textarea>Please write your comment ...</textarea>
<select name="country">
<option value="">Select your country</option>
<option value="finland">Finland</option>
<option value="sweden">Sweden</option>
<option value="denmark">Denmark</option>
<option value="norway">Norway</option>
<option value="iceland">Iceland</option>
</select>
```
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 on 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 (
<div className='App'>
<label htmlFor='firstName'>First Name: </label>
<input
type='text'
id='firstName'
name='firstName'
placeholder='First Name'
value={firstName}
onChange={this.handleChange}
/>
<h1>{this.state.firstName}</h1>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
We usually use form to handle use 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 (
<div className='App'>
<h3>Add Student</h3>
<form onSubmit={this.handleSubmit}>
<div>
<input
type='text'
name='firstName'
placeholder='First Name'
value={firstName}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='lastName'
placeholder='Last Name'
value={lastName}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='country'
placeholder='Country'
value={country}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='title'
placeholder='Title'
value={title}
onChange={this.handleChange}
/>
</div>
<button class='btn btn-success'>Submit</button>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, 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 }) => (
<option value={value}> {label}</option>
))
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 (
<div className='App'>
<h3>Add Student</h3>
<form onSubmit={this.handleSubmit}>
<div className='row'>
<div className='form-group'>
<label htmlFor='firstName'>First Name </label>
<input
type='text'
name='firstName'
value={firstName}
onChange={this.handleChange}
placeholder='First Name'
/>
</div>
<div className='form-group'>
<label htmlFor='lastName'>Last Name </label>
<input
type='text'
name='lastName'
value={this.state.lastName}
onChange={this.handleChange}
placeholder='Last Name'
/>
</div>
<div className='form-group'>
<label htmlFor='email'>Email </label>
<input
type='email'
name='email'
value={email}
onChange={this.handleChange}
placeholder='Email'
/>
</div>
</div>
<div className='form-group'>
<label htmlFor='tel'>Telephone </label>
<input
type='tel'
name='tel'
value={tel}
onChange={this.handleChange}
placeholder='Tel'
/>
</div>
<div className='form-group'>
<label htmlFor='dateOfBirth'>Date of birth </label>
<input
type='date'
name='dateOfBirth'
value={dateOfBirth}
onChange={this.handleChange}
placeholder='Date of Birth'
/>
</div>
<div className='form-group'>
<label htmlFor='favoriteColor'>Favorite Color</label>
<input
type='color'
id='color'
name='color'
value={color}
onChange={this.handleChange}
placeholder='Favorite Color'
/>
</div>
<div className='form-group'>
<label htmlFor='weight'>Weight </label>
<input
type='number'
id='weight'
name='weight'
value={weight}
onChange={this.handleChange}
placeholder='Weight in Kg'
/>
</div>
<div>
<label htmlFor='country'>Country</label> <br />
<select name='country' onChange={this.handleChange} id='country'>
{selectOptions}
</select>
</div>
<div>
<p>Gender</p>
<div>
<input
type='radio'
id='female'
name='gender'
value='Female'
onChange={this.handleChange}
checked={gender === 'Female'}
/>
<label htmlFor='female'>Female</label>
</div>
<div>
<input
id='male'
type='radio'
name='gender'
value='Male'
onChange={this.handleChange}
checked={gender === 'Male'}
/>
<label htmlFor='male'>Male</label>
</div>
<div>
<input
id='other'
type='radio'
name='gender'
value='Other'
onChange={this.handleChange}
checked={gender === 'Other'}
/>
<label htmlFor='other'>Other</label>
</div>
</div>
<div>
<p>Select your skills</p>
<div>
<input
type='checkbox'
id='html'
name='html'
onChange={this.handleChange}
/>
<label htmlFor='html'>HTML</label>
</div>
<div>
<input
type='checkbox'
id='css'
name='css'
onChange={this.handleChange}
/>
<label htmlFor='css'>CSS</label>
</div>
<div>
<input
type='checkbox'
id='javascript'
name='javascript'
onChange={this.handleChange}
/>
<label htmlFor='javascript'>JavaScript</label>
</div>
</div>
<div>
<label htmlFor='bio'>Bio</label> <br />
<textarea
id='bio'
name='bio'
value={bio}
onChange={this.handleChange}
cols='120'
rows='10'
placeholder='Write about yourself ...'
/>
</div>
<div>
<input type='file' name='file' onChange={this.handleChange} />
</div>
<div>
<button>Submit</button>
</div>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
## Form Validation
## What is validation?
The action or process of checking or proving the validity or accuracy of something in this case data.
## What is the purpose of validation
The main purpose to validation is to get a desired data from users. In addition, to prevent malicious users and data.
## Validation Types
Validation can be done in client side or sever side. At the moment, we are using React which is a front end technology and we use client side validation.A validation can implement using HTML5 built-in validation or using JavaScript(using regular expression).
In the following snippet of code, a validation has been implemented the first field. Try to understand how it works. The onBlur event has been used to check validity when the input is not focused.
```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 }) => (
<option value={value}> {label}</option>
))
class App extends Component {
// declaring state
state = {
firstName: '',
lastName: '',
email: '',
country: '',
tel: '',
dateOfBirth: '',
favoriteColor: '',
weight: '',
gender: '',
file: '',
bio: '',
skills: {
html: false,
css: false,
javascript: false,
},
touched: {
firstName: false,
lastName: 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') {
this.setState({ [name]: e.target.files[0] })
} else {
this.setState({ [name]: value })
}
}
handleBlur = (e) => {
const { name, value } = e.target
this.setState({ touched: { ...this.state.touched, [name]: true } })
}
validate = () => {
// Object to collect error feedback and to display on the form
const errors = {
firstName: '',
}
if (
(this.state.touched.firstName && this.state.firstName.length < 3) ||
(this.state.touched.firstName && this.state.firstName.length > 12)
) {
errors.firstName = 'First name must be between 2 and 12'
}
return errors
}
handleSubmit = (e) => {
/*
e.preventDefault()
stops the default behavior of form element
specifically refreshing of page
*/
e.preventDefault()
const {
firstName,
lastName,
email,
country,
gender,
tel,
dateOfBirth,
favoriteColor,
weight,
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,
country,
gender,
tel,
dateOfBirth,
favoriteColor,
weight,
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
// the noValidate attribute on the form is to stop the HTML5 built-in validation
const { firstName } = this.validate()
return (
<div className='App'>
<h3>Add Student</h3>
<form onSubmit={this.handleSubmit} noValidate>
<div className='row'>
<div className='form-group'>
<label htmlFor='firstName'>First Name </label>
<input
type='text'
name='firstName'
value={this.state.firstName}
onChange={this.handleChange}
onBlur={this.handleBlur}
placeholder='First Name'
/> <br />
<small>{firstName}</small>
</div>
<div className='form-group'>
<label htmlFor='lastName'>Last Name </label>
<input
type='text'
name='lastName'
value={this.state.lastName}
onChange={this.handleChange}
placeholder='Last Name'
/>
</div>
<div className='form-group'>
<label htmlFor='email'>Email </label>
<input
type='email'
name='email'
value={this.state.email}
onChange={this.handleChange}
placeholder='Email'
/>
</div>
</div>
<div className='form-group'>
<label htmlFor='tel'>Telephone </label>
<input
type='tel'
name='tel'
value={this.state.tel}
onChange={this.handleChange}
placeholder='Tel'
/>
</div>
<div className='form-group'>
<label htmlFor='dateOfBirth'>Date of birth </label>
<input
type='date'
name='dateOfBirth'
value={this.state.dateOfBirth}
onChange={this.handleChange}
placeholder='Date of Birth'
/>
</div>
<div className='form-group'>
<label htmlFor='favoriteColor'>Favorite Color</label>
<input
type='color'
id='favoriteColor'
name='favoriteColor'
value={this.state.favoriteColor}
onChange={this.handleChange}
placeholder='Favorite Color'
/>
</div>
<div className='form-group'>
<label htmlFor='weight'>Weight </label>
<input
type='number'
id='weight'
name='weight'
value={this.state.weight}
onChange={this.handleChange}
placeholder='Weight in Kg'
/>
</div>
<div>
<label htmlFor='country'>Country</label> <br />
<select name='country' onChange={this.handleChange} id='country'>
{selectOptions}
</select>
</div>
<div>
<p>Gender</p>
<div>
<input
type='radio'
id='female'
name='gender'
value='Female'
onChange={this.handleChange}
checked={this.state.gender === 'Female'}
/>
<label htmlFor='female'>Female</label>
</div>
<div>
<input
id='male'
type='radio'
name='gender'
value='Male'
onChange={this.handleChange}
checked={this.state.gender === 'Male'}
/>
<label htmlFor='male'>Male</label>
</div>
<div>
<input
id='other'
type='radio'
name='gender'
value='Other'
onChange={this.handleChange}
checked={this.state.gender === 'Other'}
/>
<label htmlFor='other'>Other</label>
</div>
</div>
<div>
<p>Select your skills</p>
<div>
<input
type='checkbox'
id='html'
name='html'
onChange={this.handleChange}
/>
<label htmlFor='html'>HTML</label>
</div>
<div>
<input
type='checkbox'
id='css'
name='css'
onChange={this.handleChange}
/>
<label htmlFor='css'>CSS</label>
</div>
<div>
<input
type='checkbox'
id='javascript'
name='javascript'
onChange={this.handleChange}
/>
<label htmlFor='javascript'>JavaScript</label>
</div>
</div>
<div>
<label htmlFor='bio'>Bio</label> <br />
<textarea
id='bio'
name='bio'
value={this.state.bio}
onChange={this.handleChange}
cols='120'
rows='10'
placeholder='Write about yourself ...'
/>
</div>
<div>
<input type='file' name='file' onChange={this.handleChange} />
</div>
<div>
<button>Submit</button>
</div>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
# Exercises
## Exercises: Level 1
1. What is the importance of form?
2. How many input types do you know?
3. Mention at least four attributes of an input element
4. What is the importance of htmlFor?
5. Write an input type which is not given in the example if there is?
6. What is a controlled input?
7. What do you need to write a controlled input?
8. What event type do you use to listen changes on an input field?
9. What is the value of a checked checkbox?
10. When do you use onChange, onBlur, onSubmit?
11. What is the purpose of write e.preventDefault() inside the submit handler method?
12. How do you bind data in React? The first input field example is data binding in React.
13. What is validation?
14. What is the event type we use to listen when an input changes?
15. What are event types we use to validate an input?
## Exercises: Level 2
1. Validate the form given above (a gif image or a video will be provided later). First try to validate without using any library then try it with validator.js.
2. Coming ..
## Exercises: Level 3
Coming ..
🎉 CONGRATULATIONS ! 🎉
[<< Day 11](../11_Day_Events/11_events.md) | [Day 13 >>](../13_Day_Controlled_Versus_Uncontrolled_Input/13_uncontrolled_input.md)

@ -0,0 +1,23 @@
# 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*

@ -0,0 +1,5 @@
# 30 Days of React App: Day 12
In the project directory, you can run to start the project
### `npm start`

@ -0,0 +1,34 @@
{
"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"
]
}
}

@ -0,0 +1,111 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500|Roboto:300,400,500&display=swap"
rel="stylesheet"
/>
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>30 Days Of React App</title>
<style>
/* == General style === */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
line-height: 1.5;
font-family: 'Montserrat';
font-weight: 300;
color: black;
}
.root {
min-height: 100%;
position: relative;
}
.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;
}
header {
background-color: #61dbfb;
padding: 25;
padding: 10px;
}
main {
padding: 10px;
padding-bottom: 60px;
/* Height of the footer */
}
ul {
margin-left: 15px;
}
ul li {
list-style: none;
}
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;
}
.user-card {
margin-top: 10px;
}
.user-card > img {
border-radius: 50%;
width: 14%;
}
</style>
</head>
<body>
<div id="root"></div>
</body>
</html>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,13 @@
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 },
]

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

@ -0,0 +1,326 @@
// 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 }) => (
<option value={value}> {label}</option>
))
class App extends Component {
// declaring state
state = {
firstName: '',
lastName: '',
email: '',
country: '',
tel: '',
dateOfBirth: '',
favoriteColor: '',
weight: '',
gender: '',
file: '',
bio: '',
skills: {
html: false,
css: false,
javascript: false,
},
touched: {
firstName: false,
lastName: false,
},
}
handleChange = (e) => {
/*
// we can get the name and value like this but we can also destructure it from e.target
const name = e.target.name
const value = e.target.value
*/
const { name, value, type, checked } = e.target
// [variablename] this 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') {
this.setState({ [name]: e.target.files[0] })
} else {
this.setState({ [name]: value })
}
}
handleBlur = (e) => {
const { name, value } = e.target
this.setState({ touched: { ...this.state.touched, [name]: true } })
}
validate = () => {
// Object to collect error feedback and to display on the form
const errors = {
firstName: '',
}
if (
(this.state.touched.firstName && this.state.firstName.length < 3) ||
(this.state.touched.firstName && this.state.firstName.length > 12)
) {
errors.firstName = 'First name must be between 2 and 12'
}
return errors
}
handleSubmit = (e) => {
// stops the default behavior of form element specifically refreshing of page
e.preventDefault()
const {
firstName,
lastName,
email,
country,
gender,
tel,
dateOfBirth,
favoriteColor,
weight,
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,
country,
gender,
tel,
dateOfBirth,
favoriteColor,
weight,
bio,
file,
skills: formattedSkills,
}
console.log(data)
}
render() {
// accessing the state value by destrutcturing the state
// the noValidate attribute on the form is to stop the HTML5 built-in validation
const { firstName } = this.validate()
return (
<div className='App'>
<h3>Add Student</h3>
<form onSubmit={this.handleSubmit} noValidate>
<div className='row'>
<div className='form-group'>
<label htmlFor='firstName'>First Name </label>
<input
type='text'
name='firstName'
value={this.state.firstName}
onChange={this.handleChange}
onBlur={this.handleBlur}
placeholder='First Name'
/>{' '}
<br />
<small>{firstName}</small>
</div>
<div className='form-group'>
<label htmlFor='lastName'>Last Name </label>
<input
type='text'
name='lastName'
value={this.state.lastName}
onChange={this.handleChange}
placeholder='Last Name'
/>
</div>
<div className='form-group'>
<label htmlFor='email'>Email </label>
<input
type='email'
name='email'
value={this.state.email}
onChange={this.handleChange}
placeholder='Email'
/>
</div>
</div>
<div className='form-group'>
<label htmlFor='tel'>Telephone </label>
<input
type='tel'
name='tel'
value={this.state.tel}
onChange={this.handleChange}
placeholder='Tel'
/>
</div>
<div className='form-group'>
<label htmlFor='dateOfBirth'>Date of birth </label>
<input
type='date'
name='dateOfBirth'
value={this.state.dateOfBirth}
onChange={this.handleChange}
placeholder='Date of Birth'
/>
</div>
<div className='form-group'>
<label htmlFor='favoriteColor'>Favorite Color</label>
<input
type='color'
id='favoriteColor'
name='favoriteColor'
value={this.state.favoriteColor}
onChange={this.handleChange}
placeholder='Favorite Color'
/>
</div>
<div className='form-group'>
<label htmlFor='weight'>Weight </label>
<input
type='number'
id='weight'
name='weight'
value={this.state.weight}
onChange={this.handleChange}
placeholder='Weight in Kg'
/>
</div>
<div>
<label htmlFor='country'>Country</label> <br />
<select name='country' onChange={this.handleChange} id='country'>
{selectOptions}
</select>
</div>
<div>
<p>Gender</p>
<div>
<input
type='radio'
id='female'
name='gender'
value='Female'
onChange={this.handleChange}
checked={this.state.gender === 'Female'}
/>
<label htmlFor='female'>Female</label>
</div>
<div>
<input
id='male'
type='radio'
name='gender'
value='Male'
onChange={this.handleChange}
checked={this.state.gender === 'Male'}
/>
<label htmlFor='male'>Male</label>
</div>
<div>
<input
id='other'
type='radio'
name='gender'
value='Other'
onChange={this.handleChange}
checked={this.state.gender === 'Other'}
/>
<label htmlFor='other'>Other</label>
</div>
</div>
<div>
<p>Select your skills</p>
<div>
<input
type='checkbox'
id='html'
name='html'
onChange={this.handleChange}
/>
<label htmlFor='html'>HTML</label>
</div>
<div>
<input
type='checkbox'
id='css'
name='css'
onChange={this.handleChange}
/>
<label htmlFor='css'>CSS</label>
</div>
<div>
<input
type='checkbox'
id='javascript'
name='javascript'
onChange={this.handleChange}
/>
<label htmlFor='javascript'>JavaScript</label>
</div>
</div>
<div>
<label htmlFor='bio'>Bio</label> <br />
<textarea
id='bio'
name='bio'
value={this.state.bio}
onChange={this.handleChange}
cols='120'
rows='10'
placeholder='Write about yourself ...'
/>
</div>
<div>
<input type='file' name='file' onChange={this.handleChange} />
</div>
<div>
<button>Submit</button>
</div>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,187 @@
<div align="center">
<h1> 30 Days Of React: Uncontrolled Component</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> October, 2020</small>
</sub>
</div>
[<< Day 12](../12_Day_Forms/12_forms.md) | [Day 14 >>]()
![30 Days of React banner](../images/30_days_of_react_banner_day_13.jpg)
- [Uncotrolled Components](#uncotrolled-components)
- [Getting data from an uncontrolled input](#getting-data-from-an-uncontrolled-input)
- [Getting multiple input data from form](#getting-multiple-input-data-from-form)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Uncotrolled Components
In the previous day challenge we have covered controlled inputs. In react most of the time we use controlled inputs as recommended on the official [documentation of React](https://reactjs.org/docs/uncontrolled-components.html).
To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM. In uncontrolled input we get data from input fields like traditional HTML form data handling.
An example of uncontrolled component
## Getting data from an uncontrolled input
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
firstName = React.createRef()
handleSubmit = (e) => {
e.preventDefault()
console.log(this.firstName.current.value)
}
render() {
return (
<div className='App'>
<form onSubmit={this.handleSubmit}>
<label htmlFor='firstName'>First Name: </label>
<input
type='text'
id='firstName'
name='firstName'
placeholder='First Name'
ref={this.firstName}
/>
<button type='submit'>Submit</button>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
## Getting multiple input data from form
We can grab multiple input data from DOM. We are not directly targeting the DOM but React is getting data from DOM using ref.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
firstName = React.createRef()
lastName = React.createRef()
country = React.createRef()
title = React.createRef()
handleSubmit = (e) => {
// stops the default behavior of form element specifically refreshing of page
e.preventDefault()
console.log(this.firstName.current.value)
console.log(this.lastName.current.value)
console.log(this.title.current.value)
console.log(this.country.current.value)
const data = {
firstName: this.firstName.current.value,
lastName: this.lastName.current.value,
title: this.title.current.value,
country: this.country.current.value,
}
// the is the place we connect backend api to send the data to the database
console.log(data)
}
render() {
return (
<div className='App'>
<h3>Add Student</h3>
<form onSubmit={this.handleSubmit}>
<div>
<input
type='text'
name='firstName'
placeholder='First Name'
ref={this.firstName}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='lastName'
placeholder='Last Name'
ref={this.lastName}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='country'
placeholder='Country'
ref={this.country}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='title'
placeholder='Title'
ref={this.title}
onChange={this.handleChange}
/>
</div>
<button className='btn btn-success'>Submit</button>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
Most of the time we use controlled input instead of uncontrolled input. In case if you want to target some element on the DOM you will use ref to get the content of that element. Don't touch directly using pure JavaScript. When you develop a React application do not touch the DOM directly because React has its own way of handling the DOM manipulation.
# Exercises
## Exercises: Level 1
1. What is a controlled input?
2. What is an uncontrolled input
3. How do you get a content of a certain HTML element in React ?
4. Why it is not a good idea to touch the DOM directly in React ?
5. What is most frequently used in React ? Controlled or Uncontrolled input.
6. What do you need to write uncontrolled input?
7. Does state require to write uncontrolled input?
8. When do you use uncontrolled input?
9. When do you use controlled input?
10. Do you use a controlled or uncontrolled input to validate form input fields?
## Exercises: Level 2
coming
## Exercises: Level 3
Coming
🎉 CONGRATULATIONS ! 🎉
[<< Day 12](../12_Day_Forms/12_forms.md) | [Day 14 >>]()

@ -0,0 +1,23 @@
# 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*

@ -0,0 +1,5 @@
# 30 Days of React App: Day 13
In the project directory, you can run to start the project
### `npm start`

@ -0,0 +1,34 @@
{
"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"
]
}
}

@ -0,0 +1,111 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500|Roboto:300,400,500&display=swap"
rel="stylesheet"
/>
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>30 Days Of React App</title>
<style>
/* == General style === */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
line-height: 1.5;
font-family: 'Montserrat';
font-weight: 300;
color: black;
}
.root {
min-height: 100%;
position: relative;
}
.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;
}
header {
background-color: #61dbfb;
padding: 25;
padding: 10px;
}
main {
padding: 10px;
padding-bottom: 60px;
/* Height of the footer */
}
ul {
margin-left: 15px;
}
ul li {
list-style: none;
}
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;
}
.user-card {
margin-top: 10px;
}
.user-card > img {
border-radius: 50%;
width: 14%;
}
</style>
</head>
<body>
<div id="root"></div>
</body>
</html>

@ -0,0 +1,13 @@
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 },
]

@ -0,0 +1,79 @@
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
firstName = React.createRef()
lastName = React.createRef()
country = React.createRef()
title = React.createRef()
handleSubmit = (e) => {
// stops the default behavior of form element specifically refreshing of page
e.preventDefault()
console.log(this.firstName.current.value)
console.log(this.lastName.current.value)
console.log(this.title.current.value)
console.log(this.country.current.value)
const data = {
firstName: this.firstName.current.value,
lastName: this.lastName.current.value,
title: this.title.current.value,
country: this.country.current.value,
}
// the is the place we connect backend api to send the data to the database
console.log(data)
}
render() {
return (
<div className='App'>
<h3>Add Student</h3>
<form onSubmit={this.handleSubmit}>
<div>
<input
type='text'
name='firstName'
placeholder='First Name'
ref={this.firstName}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='lastName'
placeholder='Last Name'
ref={this.lastName}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='country'
placeholder='Country'
ref={this.country}
onChange={this.handleChange}
/>
</div>
<div>
<input
type='text'
name='title'
placeholder='Title'
ref={this.title}
onChange={this.handleChange}
/>
</div>
<button className='btn btn-success'>Submit</button>
</form>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 723 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save