Merge pull request #8 from Asabeneh/master

Day#15
pull/71/head
suryazi 5 years ago committed by GitHub
commit 5d5ea053c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

1
.gitignore vendored

@ -1,5 +1,6 @@
draft.md
react-for-everyone.md
component.md
draft

@ -1886,9 +1886,9 @@ person.isMarried = true
person.getPersonInfo = function () {
let skillsWithoutLastSkill = this.skills
.splice(0, this.skills.length - 1)
.slice(0, this.skills.length - 1)
.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 fullName = this.getFullName()

@ -15,7 +15,7 @@
</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)
@ -36,6 +36,7 @@
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 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?
7. What are the files and folders inside a project folder(package.json, package-lock.json or yarn.lock, .gitignore,node_modules and public)?
8. What is your favorite code editor (I believe that it is Visual Studio Code)?
9. Add different Visual Studio Code extensions to imporve your productivity(eg. prettier, ESLint etc).
10. Try to make a different module in a different file and import it to index.js.
9. Add different Visual Studio Code extensions to improve your productivity(eg. prettier, ESLint etc).
10. Try to make a different custom module in a different file and import it to index.js.
## Exercises: Level 2
1. Import and render the following images
![Front end](../images/frontend_technologies.png)
2. 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 ! 🎉

@ -14,7 +14,7 @@
</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)
@ -28,33 +28,33 @@
- [Injecting data to JSX in React Component](#injecting-data-to-jsx-in-react-component)
- [Further on Functional components](#further-on-functional-components)
- [Exercises: Components](#exercises-components)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Components
A React component is a small reusable code which is responsible for one part of the application UI. A React application is an aggregation of components. React can help us to build reusable components. The following diagram shows different components. All the components have different border colors. In React we assemble different components together to create an application. We use JavaScript functions or classes to make components. If we use a function the component will be a functional component but if we use a class the component will be a class-based component.
A React component is a small, reusable code, which is responsible for one part of the application UI. A React application is an aggregation of components. React can help us to build reusable components. The following diagram shows different components. All the components have different border colors. In React we assemble different components together to create an application. We use JavaScript functions or classes to make components. If we use a function, the component will be a functional component, but if we use a class, the component will be a class-based component.
Components can be:
- Functional Component / Presentational Component / stateless component / Dumb component
- Class Component / Container Component/ State full component / smart component
- Functional Component / Presentational Component / Stateless Component / Dumb Component
- 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 words 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
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 the 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)
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
A JavaScript function could be either a regular function or an arrow function. There is a slight difference between a regular function and an arrow function.
A JavaScript function could be either a regular function or an arrow function. These functions are not exactly the same there is a slight difference between them.
```js
const getUserInfo = (firstName, lastName, country, title, skills) => {
@ -71,7 +71,7 @@ console.log(
## JavaScript Class
A 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
class Parent {
@ -118,7 +118,7 @@ const child = new Child(
)
```
We covered function and class in brief and React component is made of JavaScript functions or classes. Now, let's make a 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
@ -189,7 +189,7 @@ const Header = () => (
### 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.
@ -216,7 +216,7 @@ const rootElement = document.getElementById('root')
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
// index.js
@ -292,7 +292,7 @@ ReactDOM.render(<App />, rootElement)
### Injecting data to JSX in React Component
So far, we used static data on the JSX elements now let's pass different data types as dynamic data. The dynamic data could be 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 inject only strings
@ -438,15 +438,14 @@ ReactDOM.render(<App />, rootElement)
### Further on Functional components
We have transformed all the JSX elements of Day 2 to functional components and by now you are very familiar with components. Let's create more components. What is the smallest size of a component ? A component that
returns only a single HTML as JSX is considered as a small component. A button component or an alert box component or just an input field component.
We have transformed all the JSX elements of Day 2 to functional components, and by now you are very familiar with components. Let's create more components. What is the smallest size of a component? A component that returns only a single HTML as JSX is considered as a small component. A button component or an alert box component, or just an input field component.
```js
const Button = () => <button>action</button>
```
The _Button_ component is made of a single HTML button element.
Let's style this button using JavaScript style object. All CSS properties should be camelCase to make a JavaScript CSS object. If we pass 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
const buttonStyles = {
@ -458,7 +457,7 @@ const buttonStyles = {
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 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
import React from 'react'
@ -484,34 +483,35 @@ ReactDOM.render(<HexaColor />, rootElement)
# Exercises: Components
## Exercises: Level 1
1. What is a React Component ?
2. How do you make a React functional component ?
3. What is the difference between a pure JavaScript function and a functional component ?
4. How small is a React component ?
5. Can we make a button or input field component ?
6. Make a reusable Button component
7. Make a reusable InputField component ?
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)
1. What is the difference between a regular function and an arrow function?
2. What is a React Component?
3. How do you make a React functional component?
4. What is the difference between a pure JavaScript function and a functional component?
5. How small is a React component?
6. Can we make a button or input field component?
7. Make a reusable Button component.
8. Make a reusable InputField component.
9. Make a reusable alert box component with one div parent element and one p child element of the div(warning alert box, success alert box).
## Exercises: Level 2
1. Create functional components and display the following images
![Front end](../images/frontend_technologies.png)
2.Use functional component to design the following user card.
![User Card](../images/user_card_design_jsx.png)
3. Use functional component to create the following design
2. Use functional component to create the following design
![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)
2. Use functional component to design the following user card.
![User Card](../images/user_card_design_jsx.png)
🎉 CONGRATULATIONS ! 🎉
[<< Day 3](../30-Days-Of-React/03_Day_Setting_Up/03_setting_up.md) | [Day 5 >>](./05_Day_Props/05_props.md)
[<< Day 3](../30-Days-Of-React/03_Day_Setting_Up/03_setting_up.md) | [Day 5 >>](../05_Day_Props/05_props.md)

@ -35,6 +35,7 @@
- [Exercises: Components and Props](#exercises-components-and-props)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Props
@ -1079,18 +1080,20 @@ We will cover propTypes in detail in other sections.
1. Create a functional component and display the following images
![Front end](../images/frontend_technologies.png)
2.Use functional component to design the following user card.
![User Card](../images/user_card_design_jsx.png)
3. Use functional component to create the following design
2. Use functional component to create the following design
![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)
2. Use functional component to design the following user card.
![User Card](../images/user_card_design_jsx.png)
🎉 CONGRATULATIONS ! 🎉
[<< Day 4](../04_Day_Component/04_components.md) | [Day 6 >>](../06_Day_Map_List_Keys/06_map_list_keys.md)

@ -31,13 +31,13 @@
# 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
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
import React from 'react'
@ -57,7 +57,7 @@ const rootElement = document.getElementById('root')
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
@ -183,7 +183,7 @@ ReactDOM.render(<App />, rootElement)
### 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
import React from 'react'
@ -279,7 +279,7 @@ ReactDOM.render(<App />, rootElement)
## 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)

@ -14,7 +14,7 @@
</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)
@ -24,10 +24,11 @@
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Class Components
In the previous sections, we have covered JSX, functional component and props. In this section, we will cover class components or 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.
@ -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
## Exercises: Level 3
Coming ...
🎉 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">
<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/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -18,7 +18,7 @@
![30 Days of React banner](../images/30_days_of_react_banner_day_8.jpg)
- [State](#state)
- [States](#states)
- [What is State?](#what-is-state)
- [How to set a state](#how-to-set-a-state)
- [Resetting a state using a JavaScript method](#resetting-a-state-using-a-javascript-method)
@ -27,7 +27,7 @@
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# State
# States
## What is State?

@ -14,7 +14,7 @@
</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)
@ -777,4 +777,4 @@ Coming
🎉 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,5 +1,5 @@
<div align="center">
<h1> 30 Days Of React: Statet</h1>
<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>
@ -14,7 +14,7 @@
</div>
[<< Day 9](../09_Day_Conditional_Rendering/09_conditional_rendering.md) | [Day 11 >>](../11_Day_Events/10_events.md)
[<< 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)
@ -26,6 +26,7 @@
- [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
@ -611,8 +612,12 @@ Well done. Time to do some exercises for your brain and muscles.
## Exercises:Level 2
1. Make a simple a simple portfolio using the components we have created so far.
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/10_events.md)
[<< Day 9](../09_Day_Conditional_Rendering/09_conditional_rendering.md) | [Day 11 >>](../11_Day_Events/11_events.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of React: Statet</h1>
<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>
@ -122,10 +122,6 @@ Let's implement some more mouse and keyboard events.
// index.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
/*
_onMouseMove, onMouseEnter, onMouseLeave, onMouseOut, onClick, onKeyDown, onKeyPress, onKeyUp, onCopy, onCut, onDrag, onChange,onBlur,onInput, onSubmit_
*/
class App extends Component {
state = {
@ -217,6 +213,17 @@ ReactDOM.render(<App />, rootElement)
## 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
@ -225,6 +232,8 @@ Implement the following using onMouseEnter event
## 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)

@ -14,7 +14,7 @@
</div>
[<< Day 11](../11_Day_Events/11_events.md) | [Day 13 >>]()
[<< 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)
@ -106,7 +106,11 @@ class App extends Component {
}
render() {
// accessing the state value and this value will injected to the input in the value attribute
/*
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'>
@ -139,7 +143,7 @@ In this section we will develop a small form which collect user information. Our
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
// declaring state
// declaring initial state
state = {
firstName: '',
lastName: '',
@ -148,17 +152,29 @@ class App extends Component {
}
handleChange = (e) => {
/*
// we can get the name and value like this but we can also destructure it from e.target
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] 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
// [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) => {
// stops the default behavior of form element specifically refreshing of page
/*
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)
}
@ -277,12 +293,15 @@ class App extends React.Component {
}
handleChange = (e) => {
/*
// we can get the name and value like this but we can also destructure it from e.target
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] 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
/*
[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({
@ -296,7 +315,11 @@ class App extends React.Component {
}
}
handleSubmit = (e) => {
// stops the default behavior of form element specifically refreshing of page
/*
e.preventDefault()
stops the default behavior of form element
specifically refreshing of page
*/
e.preventDefault()
const {
firstName,
@ -334,6 +357,10 @@ class App extends React.Component {
file,
skills: formattedSkills,
}
/*
the is the place where we connect backend api
to send the data to the database
*/
console.log(data)
}
@ -610,12 +637,15 @@ class App extends Component {
}
handleChange = (e) => {
/*
// we can get the name and value like this but we can also destructure it from e.target
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] 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
/*
[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({
@ -646,7 +676,11 @@ class App extends Component {
return errors
}
handleSubmit = (e) => {
// stops the default behavior of form element specifically refreshing of page
/*
e.preventDefault()
stops the default behavior of form element
specifically refreshing of page
*/
e.preventDefault()
const {
@ -685,7 +719,10 @@ class App extends Component {
file,
skills: formattedSkills,
}
// the is the place we connect backend api to send the data to the database
/*
the is the place where we connect backend api
to send the data to the database
*/
console.log(data)
}
@ -889,17 +926,25 @@ ReactDOM.render(<App />, rootElement)
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. How do you bind data in React? The first input field example is data binding in React.
8. What is validation?
9. What is the event type we use to listen when an input changes?
10. What are event types we use to validate an 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 >>]()
[<< Day 11](../11_Day_Events/11_events.md) | [Day 13 >>](../13_Day_Controlled_Versus_Uncontrolled_Input/13_uncontrolled_input.md)

@ -168,11 +168,20 @@ Most of the time we use controlled input instead of uncontrolled input. In case
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,519 @@
<div align="center">
<h1> 30 Days Of React:Component Life Cycles</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 13](../13_Day_Controlled_Versus_Uncontrolled_Input/13_uncontrolled_input.md) | [Day 15 >>]()
![30 Days of React banner](../images/30_days_of_react_banner_day_14.jpg)
- [Component Life Cycles](#component-life-cycles)
- [What is component life cycle](#what-is-component-life-cycle)
- [Mounting](#mounting)
- [Contructor](#contructor)
- [getDerivedStateFromPros](#getderivedstatefrompros)
- [Render](#render)
- [ComponentDidMount](#componentdidmount)
- [Updating](#updating)
- [getDerivedStateFromProps](#getderivedstatefromprops)
- [shouldComponentUpdate](#shouldcomponentupdate)
- [render](#render-1)
- [componentDidUpdate](#componentdidupdate)
- [Unmounting](#unmounting)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Component Life Cycles
## What is component life cycle
Component life cycle is the process of mounting, updating and destroying a component in a React application. You can associate a component life cycle with the process of human growth:birth, adult, elderly and death.
In React component also a component can be mounted or rendered the first time, can be updated by changing the data and also can be destroyed whenever it is not needed. In React each component has three main phases:
- Mounting
- Updating
- Unmounting
## Mounting
Rendering or putting React component into the DOM is called mounting. The following built-in methods run in the given order during mounting of a React component.
1. constructor()
2. static getDerivedStateFromProps()
3. render()
4. componentDidMount()
When we have been making a class-based component we used a built-in render method and it is required in all class-based components but other methods are optional. See the order of execution of the different methods by running the following snippet of codes.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: '',
}
}
static getDerivedStateFromProps(props, state) {
console.log(
'I am getDerivedStateFromProps and I will be the second to run.'
)
return null
}
componentDidMount() {
console.log('I am componentDidMount and I will be last to run.')
}
render() {
console.log('I am render and I will be the third to run.')
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
### Contructor
Nowadays we write class based-component without a constructor and we can write the state also outside the constructor. In older version React we the state used be always inside the constructor.
The constructor() method is executed before any other methods, when component is initiated and it is the place where to set the initial state and other values.
In class we use constructor parameter to inherit from parents and in React to the constructor take a props parameter and the super method has to be also called.
Look at the snippet of code about constructor and state.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: '',
}
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
<h2>The constructor is the first to Run</h2>
<p>Author:{this.state.firstName}</p>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
### getDerivedStateFromPros
As we can understand from the name, this method derives a state from props. The getDerivedStateFromProps() method is called right before rendering the component in the DOM. This the right place to set the state object based on the initial props.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
const User = ({ firstName }) => (
<div>
<h1>{firstName}</h1>
</div>
)
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
// we can write state inside or outside the constructor
// if is written outside the constructor it does not need the keyword this
this.state = {
firstName: 'John',
}
}
static getDerivedStateFromProps(props, state) {
console.log(
'I am getDerivedStateFromProps and I will be the second to run.'
)
return { firstName: props.firstName }
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
<h3>getDerivedStateFromProps</h3>
<User firstName={this.state.firstName} />
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App firstName='Asabeneh' />, rootElement)
```
### Render
The render method is a required method when we create a class-based component. The render method is where we return JSX. The render methods render whenever there is change in state. Do not set your state inside render method.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
const User = ({ firstName }) => (
<div>
<h1>{firstName}</h1>
</div>
)
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
// we can write state inside or outside the constructor
// if is written outside the constructor it does not need the keyword this
this.state = {
firstName: 'John',
}
}
render() {
// Never do this
// Do not reset inside the render method, create a method to reset the state
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
<h3>Render method</h3>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App firstName='Asabeneh' />, rootElement)
```
### ComponentDidMount
As we can understand the name of the method that this method called after component is render. This a place place to setting time interval and calling API. Look at the following setTimeout implementation in componentDidMount method.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: 'John',
}
}
componentDidMount() {
console.log('I am componentDidMount and I will be last to run.')
// after 3 seconds it resets the state
setTimeout(() => {
this.setState({
firstName: 'Asabeneh',
})
}, 3000)
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
<h2>componentDidMount Method</h2>
{this.state.firstName}
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
In the above snippet of code, we saw how to implement setTimeout inside a componentDidMount method. In next example, we will implement an API call using fetch.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: 'John',
data: [],
}
}
componentDidMount() {
console.log('I am componentDidMount and I will be last to run.')
const API_URL = 'https://restcountries.eu/rest/v2/all'
fetch(API_URL)
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
this.setState({
data,
})
})
.catch((error) => {
console.log(error)
})
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
<h1>Calling API</h1>
<div>
<p>There are {this.state.data.length} countries in the api</p>
<div className='countries-wrapper'>
{this.state.data.map((country) => (
<div>
<div>
{' '}
<img src={country.flag} alt={country.name} />{' '}
</div>
<div>
<h1>{country.name}</h1>
<p>Capital: {country.capital}</p>
<p>Population: {country.population}</p>
</div>
</div>
))}
</div>
</div>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
Sometimes it is better to have a separate method to render the data. See the example below:
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: 'John',
data: [],
}
}
componentDidMount() {
console.log('I am componentDidMount and I will be last to run.')
const API_URL = 'https://restcountries.eu/rest/v2/all'
fetch(API_URL)
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
this.setState({
data,
})
})
.catch((error) => {
console.log(error)
})
}
renderCountries = () => {
return this.state.data.map((country) => {
const languageOrLanguages =
country.languages.length > 1 ? 'Langauges' : 'Language'
const formatLanguages = country.languages
.map(({ name }) => name)
.join(', ')
return (
<div>
<div>
{' '}
<img src={country.flag} alt={country.name} />{' '}
</div>
<div>
<h1>{country.name}</h1>
<p>Capital: {country.capital}</p>
<p>
{languageOrLanguages}: {formatLanguages}
</p>
<p>Population: {country.population}</p>
</div>
</div>
)
})
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
<h1>Calling API</h1>
<div>
<p>There are {this.state.data.length} countries in the api</p>
<div className='countries-wrapper'>{this.renderCountries()}</div>
</div>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
## Updating
After a component has been mounted on the DOM, it can be updated when a state or props change. An update of a React component can be caused by changes to props or state . These methods are called in the following order when a component is being re-rendered:
1. static getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
### getDerivedStateFromProps
Similar to the mounting phase, getDerivedStateFromProps can be also called in the updating phase. The getDerivedStateFromProps is the first method that is called when a component gets updated.
### shouldComponentUpdate
The shouldComponentUpdate() built-in life cycle method should return a boolean. If this method does not return true the application will not update.
If the method does not return true the application will never update. This can be used for instance to block use when it reaches to a certain point(game, subscription) or may be to block a certain user.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: 'John',
data: [],
}
}
shouldComponentUpdate(nexProps, nextState) {
console.log(nextProps, nextState)
// if the return is true, the application will never update.
return true
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
### render
As we have mentioned it on the mounting phase of the component, the render() method is called when a component gets updated. It has to re-render the HTML to the DOM, with the new changes.
### componentDidUpdate
The componentDidUpdate method takes two parameters: the prevProps and prevState. It is called after the component is updated in the DOM.
```js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: 'John',
data: [],
}
}
componentDidUpdate(prevProps, prevState) {
console.log(prevState, prevProps)
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
## Unmounting
The final phase in the lifecycle of a component is unmounting. The unmounting phase removes component from the DOM.
The componentWillUnmount method is the only built-in method that gets called when a component is unmounted.
# Exercises
## Exercises: Level 1
1. What is component life cycles
2. What is the purpose of life cycles
3. What are the three stages of a component life cycle
4. What does mounting means?
5. What does updating means
6. What does unmounting means?
7. What is the most common built-in mounting life cycle method
8.
## Exercises: Level 2
## Exercises: Level 3
🎉 CONGRATULATIONS ! 🎉
[<< Day 13](../13_Day_Controlled_Versus_Uncontrolled_Input/13_uncontrolled_input.md) | [Day 15 >>]()

@ -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 14
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 },
]

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,72 @@
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
class App extends Component {
constructor(props) {
super(props)
console.log('I am the constructor and I will be the first to run.')
this.state = {
firstName: 'John',
data: [],
}
}
componentDidMount() {
console.log('I am componentDidMount and I will be last to run.')
const API_URL = 'https://restcountries.eu/rest/v2/all'
fetch(API_URL)
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
this.setState({
data,
})
})
.catch((error) => {
console.log(error)
})
}
renderCountries = () => {
return this.state.data.map((country) => {
const languageOrLanguages =
country.languages.length > 1 ? 'Langauges' : 'Language'
const formatLanguages = country.languages
.map(({ name }) => name)
.join(', ')
return (
<div>
<div>
{' '}
<img src={country.flag} alt={country.name} />{' '}
</div>
<div>
<h1>{country.name}</h1>
<p>Capital: {country.capital}</p>
<p>
{languageOrLanguages}: {formatLanguages}
</p>
<p>Population: {country.population}</p>
</div>
</div>
)
})
}
render() {
return (
<div className='App'>
<h1>React Component Life Cycle</h1>
<h1>Calling API</h1>
<div>
<p>There are {this.state.data.length} countries in the api</p>
<div className='countries-wrapper'>{this.renderCountries()}</div>
</div>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

@ -36,7 +36,7 @@
|11|[Events](./11_Day_Events/11_events.md)|
|12|[Forms](./12_Day_Forms/12_forms.md)|
|13|[Controlled and Uncontrolled Component](./13_Day_Controlled_Versus_Uncontrolled_Input/13_uncontrolled_input.md)|
|14|[Component Life Cycles😞]()|
|14|[Component Life Cycles](./14_Day_Component_Life_Cycles/14_component_life_cycles.md)|
|15|[Styles in React😞]()|

Loading…
Cancel
Save