4 |
5 | Support [**Asabeneh**](https://www.patreon.com/asabeneh?fan_landing=true) to create more educational materials
6 | [](https://www.patreon.com/asabeneh?fan_landing=true)
7 |
8 |
9 | - [Introduction](#introduction)
10 | - [1. What is React ?](#1-what-is-react-)
11 | - [Exercises](#exercises)
12 | - [2. Why React ?](#2-why-react-)
13 | - [Exercises: React](#exercises-react)
14 | - [3. JSX](#3-jsx)
15 | - [Exercises](#exercises-1)
16 | - [JSX Element](#jsx-element)
17 | - [Exercises:JSX](#exercisesjsx)
18 | - [Rendering JSX Element](#rendering-jsx-element)
19 | - [Style and className](#style-and-classname)
20 | - [Exercises - Inline Style](#exercises---inline-style)
21 | - [Exercises - Internal Styles](#exercises---internal-styles)
22 | - [Injecting data to JSX Element](#injecting-data-to-jsx-element)
23 | - [Injecting a string to JSX Element](#injecting-a-string-to-jsx-element)
24 | - [Injecting a number to JSX Element](#injecting-a-number-to-jsx-element)
25 | - [Injecting an array to JSX Element](#injecting-an-array-to-jsx-element)
26 | - [Injecting an object to JSX Element](#injecting-an-object-to-jsx-element)
27 | - [Exercise: Inject data to JSX](#exercise-inject-data-to-jsx)
28 | - [Component](#component)
29 | - [Rendering components](#rendering-components)
30 | - [Class Components](#class-components)
31 | - [Props](#props)
32 | - [Props in Functional Component](#props-in-functional-component)
33 | - [propTypes](#proptypes)
34 | - [defaultProps](#defaultprops)
35 | - [Destructuring props](#destructuring-props)
36 | - [Props in Class Components](#props-in-class-components)
37 | - [Rendering lists](#rendering-lists)
38 | - [Creating a react project](#creating-a-react-project)
39 | - [Events](#events)
40 | - [State](#state)
41 | - [Controlled input](#controlled-input)
42 | - [Forms](#forms)
43 | - [Container and Presentation component](#container-and-presentation-component)
44 | - [Controlled and uncontrolled inputs](#controlled-and-uncontrolled-inputs)
45 | - [Conditional Rendering](#conditional-rendering)
46 | - [Using if condition](#using-if-condition)
47 | - [Using ternary operators](#using-ternary-operators)
48 | - [Using and operator](#using-and-operator)
49 | - [Component Life cycles](#component-life-cycles)
50 | - [React Router](#react-router)
51 | - [React Hooks](#react-hooks)
52 |
53 | ## Introduction
54 |
55 | Prerequisite to get started with React. You should have a good understanding of the following technologies:
56 |
57 | - HTML
58 | - CSS
59 | - JavaScript
60 |
61 | If you have the above skills you will enjoy doing react.
62 | React for Everyone contains anything you need to know about react. In every section, it has some exercise and mini-projects and it is recommended to work them.
63 |
64 | ## 1. What is React ?
65 |
66 | React is a JavaScript library for building user interfaces. It was initially released on May 29, 2013. The current version is 16.12.0 and somehow it is stable. React was created by Facebook. It is a tool for building UI components. When we work with react we do not interact directly with the DOM. React has its own way to handle the DOM(Document Object Model) manipulation which is the virtual DOM. Do not directly interact with DOM when you build react application leave that job for the virtual DOM.
67 |
68 | To summarize:
69 |
70 | - React was released in May 2013
71 | - React was created by Facebook
72 | - React is a JavaScript library for building user interfaces
73 | - React is used to build single page applications- An application which has only one HTML page.
74 | - React allows us to create reusable UI components
75 | - React latest release is 16.12.0
76 |
77 | ### Exercises
78 |
79 | 1. What is React?
80 | 2. What is a library ?
81 | 3. What is single page application ?
82 | 4. What is component ?
83 | 5. What is the latest version of react ?
84 | 6. What is DOM ?
85 |
86 | ## 2. Why React ?
87 |
88 | React is one of the most popular JavaScript library. Many developers and companies have been using it for the last couple of years. Its popularity has been growing fast and it has a huge community. How do we measure popularity? One measure of could be github, let us compare the popularity of [react](https://github.com/facebook/react) and [vue](https://github.com/vuejs/vue). As of today, the popularity between the two most popular JavaScript looks like as follows. From the diagram you can tell yourself which is more popular, I will leave this for you.
89 |
90 | React Official Github Repository
91 |
92 | 
93 |
94 | Vue Official Github Repository
95 |
96 | 
97 |
98 | Why we choose to use react ? We use react because of the following reasons:
99 |
100 | - fast
101 | - modular
102 | - scalable
103 | - flexible
104 | - big community and popular
105 | - open source
106 |
107 | ### Exercises: React
108 |
109 | 1. Why you chose to use react?
110 | 2. How measures do you use to know popularity ?
111 | 3. What is more popular, react or vue ?
112 |
113 | ## 3. JSX
114 |
115 | JSX stands for JavaScript XML. JSX allows us to write HTML elements with JavaScript code. An HTML element has an opening and closing tag, content, and attribute in the opening tag. However, some HTML tag may not have a content and a closing tag, they are self closing elements. To create HTML elements in React we do not use the _createElement()_ instead we just use JSX elements. Therefore, JSX makes it easier to write and add HTML elements in React. JSX will be converted to JavaScript on browser using transpiler which [babel.js](https://babeljs.io/). Babeb is a library which transpile JSX to pure JavaScript and latest JavaScript to older version. See the JSX code below.
116 |
117 | ```js
118 | const jsxElement =
I am a JSX element
119 | ```
120 |
121 | The above strange looking code seems a JavaScrip but it is not JavaScript and it seems an HTML but not completely an HTML element. It is a mix of JavaScript and and an HTML element. JSX can allow us to use HTML in JavaScript. The HTML element in the above JSX is h1.
122 |
123 | ### Exercises
124 |
125 | 1. What is an HTML element ?
126 | 2. Write a self closing elements ?
127 | 3. What is HTML attribute, write some HTML attributes
128 | 4. What is JSX ?
129 | 5. What is babel ?
130 | 6. What is a transpiler?
131 |
132 | ## JSX Element
133 |
134 | As you have seen in the above example, JSX has a JavaScript and HTML like syntax. JSX element could be a single HTML element or many HTML elements wrapped in a parent HTML element.
135 |
136 | This JSX element has only on HTML element which is h1.
137 |
138 | ```js
139 | const jsxElement =
I am a JSX element
140 | ```
141 |
142 | Let's make more JSX elements by declaring a new variable name title and content inside h1.
143 |
144 | ```js
145 | const title =
Getting Started React
146 | ```
147 |
148 | Let us add a subtitle to the above JSX element by adding additional HTML element. Every HTML element should be wrapped by an outer HTML element to create a valid JSX element. The name title variable also should be changed to header because our JSX element is containing almost all the header of the application.
149 |
150 | ```js
151 | const header = (
152 |
153 |
Getting Started React
154 |
JavaScript Library
155 |
156 | )
157 | ```
158 |
159 | Let us keep adding more elements. Additional HTML element to display the author name and year.
160 |
161 | ```js
162 | const header = (
163 |
164 |
Getting Started React
165 |
JavaScript Library
166 |
Asabeneh Yetayeh
167 |
Feb 10, 2020
168 |
169 | )
170 | ```
171 |
172 | As you can see the header element is a parent element for all the inner HTML elements and JSX must be wrapped by an outer parent element. Without the header HTML element or other parent HTML element the above JSX is invalid.
173 |
174 | ### Exercises:JSX
175 |
176 | 1. What is JSX element
177 | 2. Write you name in JSX element and store it in a name variable
178 | 3. Write a JSX element which displays your full name, country, title, gender, email, phone number. Use h1 for the name and p for the rest of the information and store it in a user variable.
179 | 4. Write a footer JSX element
180 |
181 | ## Rendering JSX Element
182 |
183 | To render a JSX element to HTML document. We should create on index HTML. The index.html is the only HTML file you will have in any react application. That is why every react application is a single page application. Let us create an index.html file.
184 |
185 | ```html
186 |
187 |
188 |
189 |
190 |
191 | React For Everyone
192 |
193 |
194 |
195 |
196 |
197 |
200 |
201 |
202 | ```
203 |
204 | As you can see from the above index.html, we have one div with a class root and script. The root div is the get way to connect all react component to the index.html. In the script tag, we will write our JavaScript but the script type will be babel. Babel will transpile the react JSX to pure JavaScript on the browser. Let us add babel to the script. Inside the babel, we can write any pure JavaScript, JSX and in general react code.
205 |
206 | ```html
207 |
208 |
209 |
210 |
211 |
212 | React For Everyone
213 |
214 |
215 |
216 |
217 |
218 |
221 |
222 |
223 | ```
224 |
225 | The babel library is linked to our document and now we can make use of it. The next step is importing React and ReactDOM using CDN or link. Attach the react and react-dom to your file. To test if react is connected to the index.html try to check by doing console.log(React). If you see an object containing react methods then you are connected to react.
226 |
227 | ```html
228 |
229 |
230 |
231 |
232 |
233 | React For Everyone
234 |
235 |
236 |
237 |
238 |
239 |
243 |
247 |
248 |
251 |
252 |
253 | ```
254 |
255 | Now the index.html has everything we need to write react code. Let us get the root element using document.querySelect('.root') and assign it to variable name rootElement. The is the only place we directly interact with DOM.
256 |
257 | Now, you knew JSX and JSX element. Let us render the JSX element on the browser, in order to do so we need the react and ReactDOM library. In addition to the React and ReactDOM we need babel to transpile the JSX to JavaScript code. The ReactDOM package has a method render. The render method takes two arguments:a JSX element or a component and the root document. See the code below. [Live on code pen](https://codepen.io/Asabeneh/full/JjdbjqK).
258 |
259 | ```html
260 |
261 |
262 |
263 |
264 |
265 | React For Everyone
266 |
267 |
268 |
269 |
270 |
271 |
275 |
279 |
280 |
291 |
292 |
293 | ```
294 |
295 | 
296 |
297 | Let us render more content. To render more content the JSX element should have more HTML elements. For instance, we can create a header of a website and header may have a title, subtitle, author or date etc.
298 | [Live on code pen](https://codepen.io/Asabeneh/full/QWbGWeY).
299 |
300 | ```html
301 |
302 |
303 |
304 |
305 |
306 | React For Everyone
307 |
308 |
309 |
310 |
311 |
312 |
316 |
320 |
321 |
339 |
340 |
341 | ```
342 |
343 | 
344 |
345 | We have created a JSX element for the header of the website. How about the main and the footer for the website? Similar to the header, let us create a JSX element for the main and the footer.
346 |
347 | JSX element for the main part of the website.
348 |
349 | ```js
350 | // JSX element
351 | const main = (
352 |
353 |
Prerequisite to get started react.js:
354 |
355 |
HTML
356 |
CSS
357 |
JavaScript
358 |
359 |
360 | )
361 | ```
362 |
363 | JSX element for the footer part of the website.
364 |
365 | ```js
366 | // JSX element
367 | const footer = (
368 |
371 | )
372 | ```
373 |
374 | Now, we have three JSX elements:the header, main and footer. The best way to render all the three JSX elements is by wrapping them all in a parent JSX element. To include JSX element inside another JSX element we use the curly bracket, {} and call the name of the JSX inside the curly bracket.
375 |
376 | ```js
377 | // JSX element for the header part of the website
378 | const header = (
379 |
380 |
Getting Started React
381 |
JavaScript Library
382 |
Asabeneh Yetayeh
383 |
Feb 10, 2020
384 |
385 | )
386 |
387 | // JSX element for the main part of the website
388 | const main = (
389 |
390 |
Prerequisite to get started react.js:
391 |
392 |
HTML
393 |
CSS
394 |
JavaScript
395 |
396 |
397 | )
398 |
399 | // JSX element for the footer part of the website
400 | const footer = (
401 |
404 | )
405 |
406 | // JSX element which contain all, it is a container or parent
407 | const app = (
408 |
409 | {header}
410 | {main}
411 | {footer}
412 |
413 | )
414 | ```
415 |
416 | Now, let us put everything together and render it to the browser. [Live on code pen](https://codepen.io/Asabeneh/full/MWwbYWg).
417 |
418 | ```html
419 |
420 |
421 |
422 |
423 |
424 | React For Everyone
425 |
426 |
427 |
428 |
429 |
430 |
434 |
438 |
439 |
485 |
486 |
487 | ```
488 |
489 | 
490 |
491 | ## Style and className
492 |
493 | So far, we did apply any style. Now, let us add style to our JSX elements. Inline style became very popular after the emergence of react. Let us add border to the header JSX element.
494 |
495 | To add style to a JSX element we use inline style or className. We inject the style object using {}. Every CSS properties become a key and every CSS properties value become value for the the object. For instance, in the example below, border is a key and '2px solid orange' is a value, color is a key and 'black' is a value, fontSize is a key and '18px' is a value. All two word CSS properties will change to camelCase when we use them as key in the CSS object in react or JavaScript.[Live on code pen](https://codepen.io/Asabeneh/full/ZEGBYbY).
496 |
497 | ```js
498 | const header = (
499 |
500 |
517 |
518 | )
519 | ```
520 |
521 | Let us apply some style to our JSX elements and see the result.
522 |
523 | .
524 |
525 | Now, lets us apply style the header part only [Live on code pen](https://codepen.io/Asabeneh/full/ZEGBYBG).
526 |
527 | It is good practice to open the browser console while you are developing your application to know if everything goes well.
528 |
529 | Let us keep styling all the JSX elements we have created: the header, main and footer. We can also use regular internal styling to style our application. Using regular style, to target an HTML element we use tag name, id, class, an attribute and other methods. It is very common in the react developer community people use quite a lot classes instead of id. In this material, I will use only class instead of id.
530 |
531 | In JSX element we write className instead of class because class is a reserved word in JavaScript. Similar to className, htmlFor instead of for in label tag. See the example below.
532 |
533 | ```js
534 | const title =
Getting Started React
535 | const inputField = (
536 |
537 |
538 |
539 |
540 | )
541 | ```
542 |
543 | The id used in the input element is not for styling purpose instead to refer the label to the input field.
544 |
545 | If class is used instead of className or for instead of htmlFor you will see such kind of warning.
546 |
547 | 
548 |
549 | Now, you know how to use the inline style and how to use className and let us style all the JSX elements.
550 |
551 | ```html
552 |
553 |
554 |
555 |
556 |
557 | React For Everyone
558 |
559 |
560 |
561 |
562 |
563 |
567 |
571 |
572 |
633 |
634 |
635 | ```
636 |
637 | 
638 |
639 | ### Exercises - Inline Style
640 |
641 | 1. Create a style object for the main JSX
642 | 2. Create a style object for the footer and app JSX
643 | 3. Add more styles to the JSX elements
644 |
645 | Instead of style object using regular styling method is more easier than the above. Now, let us use internal style to style all the JSX. It is also possible to use external style method.[Live on code pen](https://codepen.io/Asabeneh/full/QWbGwge)
646 |
647 | ```html
648 |
649 |
650 |
651 |
652 |
653 |
657 |
658 | React For Everyone
659 |
739 |
740 |
741 |
742 |
743 |
744 |
748 |
752 |
753 |
810 |
811 |
812 | ```
813 |
814 | 
815 |
816 | ### Exercises - Internal Styles
817 |
818 | 1. Apply different styles to you JSX elements
819 |
820 | ## Injecting data to JSX Element
821 |
822 | So far, we used static data on the JSX elements but we also pass different data types as a dynamic data. The dynamic data could be string, number, boolean, array or object. Let us see each of the data types step by step. To inject data to a JSX we use the {} bracket.
823 |
824 | ```js
825 | const title = 'Getting Started React'
826 | const subtitle = 'JavaScript Library'
827 | const authorFirstName = 'Asabeneh'
828 | const authorLastName = 'Yetayeh'
829 | const date = 'Feb 10, 2020'
830 |
831 | // JSX element, header
832 | const header = (
833 |
834 |
890 | ```
891 |
892 | As you can see in the above example, it is possible to do some arithmetic calculation and ternary operations.
893 |
894 | ### Injecting an array to JSX Element
895 |
896 | To give example for an array, let us change the HTML, CSS, JavaScript an array and inject it to the main JSX element below. We will cover in much detail in rendering lists section.
897 |
898 | ```js
899 | const techs = ['HTML', 'CSS', 'JavaScript']
900 |
901 | // JSX element, main
902 | const main = (
903 |
904 |
905 |
906 | Prerequisite to get started{' '}
907 |
908 | react.js
909 |
910 | :
911 |
912 |
{techs}
913 |
914 |
915 | )
916 | ```
917 |
918 | ### Injecting an object to JSX Element
919 |
920 | We can inject string, number, boolean, array data to JSX but we can not directly inject object. We should extract object values first or destructure the content of the object before we inject to the JSX element. For instance, let us write firstName and lastName inside an object and extract them out to use them inside JSX.
921 |
922 | Now, let us put everything together. Here in the example below, the data is injected dynamically to the JSX. [Live on code pen](https://codepen.io/Asabeneh/full/YzXWgpZ)
923 |
924 | ```html
925 |
926 |
927 |
928 |
929 |
930 |
934 |
935 | React For Everyone
936 |
1016 |
1017 |
1018 |
1019 |
1020 |
1021 |
1025 |
1029 |
1030 |
1114 |
1115 |
1116 | ```
1117 |
1118 | 
1119 |
1120 | As you can see the lists are all in one line. Therefore, we should format the list the way we want before we inject to JSX. In order to format the list we should modify the array before we inject it to JSX. We can modify the array using _map_. As a react developer you should have a very good understanding of functional programming(map, filter, reduce, find, some, every).
1121 |
1122 | ```js
1123 | const techs = ['HTML', 'CSS', 'JavaScript']
1124 | const techsFormatted = techs.map(tech =>
{tech}
)
1125 | ```
1126 |
1127 | In the following code example, the list is now containing list elements and formatted properly.
1128 |
1129 | ```html
1130 |
1131 |
1132 |
1133 |
1134 |
1135 |
1139 |
1140 | React For Everyone
1141 |
1221 |
1222 |
1223 |
1224 |
1225 |
1226 |
1230 |
1234 |
1235 |
1320 |
1321 |
1322 | ```
1323 |
1324 | Rendering list
1325 |
1326 | 
1327 | As you can see above, now the lists are formatted properly but there is warning on the console which says each list child should have a unique key. In the array, we do not have id but it is common to pass id as a unique when you have id in your data. Now, let us just pass each items us a unique key and remove the warning.
1328 |
1329 | ```html
1330 |
1331 |
1332 |
1333 |
1334 |
1335 |
1336 |
1339 |
1340 |
1341 | React For Everyone
1342 |
1429 |
1430 |
1431 |
1432 |
1433 |
1434 |
1435 |
1436 |
1437 |
1525 |
1526 |
1527 |
1528 |
1529 | ```
1530 |
1531 | 
1532 |
1533 | Now, you have a very good understanding of how to create JSX element and also how to inject data to JSX. In the next section, we will talk about component which are more powerful and useful than JSX.
1534 |
1535 | ### Exercise: Inject data to JSX
1536 |
1537 | 1. Practice how to make JSX element and injecting dynamic data(string, number, boolean, array, object)
1538 |
1539 | ## Component
1540 |
1541 | 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.
1542 |
1543 | Components can be:
1544 |
1545 | - Functional Component / Presentational Component / stateless component / Dumb components
1546 | - Class Component / Container Component/ State full component / smart components
1547 |
1548 | 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.
1549 |
1550 | 
1551 |
1552 | 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.
1553 |
1554 | ```js
1555 | // React component stntax
1556 | // it can be arrow function, function declaration or function expression
1557 | const ComponentName = () => {
1558 | return JSX
1559 | }
1560 | ```
1561 |
1562 | ```js
1563 | // JSX element, header
1564 | const header = (
1565 |
1566 |
1591 |
1592 | )
1593 | }
1594 |
1595 | // Even th above code can be written like this
1596 | const Header = () => (
1597 |
1598 |
1599 |
Getting Started React
1600 |
JavaScript Library
1601 |
Asabeneh Yetayeh
1602 |
Feb 10, 2020
1603 |
1604 |
1605 | )
1606 | ```
1607 |
1608 | ## Rendering components
1609 |
1610 | Now, lets change all the JSX elements we had to components. When we call JSX element we use curly brackets and when we call components we do as follows . If we pass an attribute when we call the component name, we call it props(). We will talk about props in its section.[Live on code pen](https://codepen.io/Asabeneh/full/wvaKKEM)
1611 |
1612 | ```html
1613 |
1614 |
1615 |
1616 |
1617 |
1618 |
1622 |
1623 | React For Everyone
1624 |
1704 |
1705 |
1706 |
1707 |
1708 |
1709 |
1713 |
1717 |
1718 |
1774 |
1775 |
1776 | ```
1777 |
1778 | 
1779 |
1780 | ### Class Components
1781 |
1782 | All the above 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. [Live on code pen](https://codepen.io/Asabeneh/full/oNXjpOj)
1783 |
1784 | ```js
1785 | // Header Component
1786 | // Functional component
1787 | const Header = () => (
1788 |
1789 |
1895 | )
1896 |
1897 | // The App, or the parent or the container component
1898 | // Class Component
1899 | class App extends React.Component {
1900 | render() {
1901 | return (
1902 |
1903 |
1904 |
1905 |
1906 |
1907 | )
1908 | }
1909 | }
1910 | ```
1911 |
1912 | Most of the time the container or the parent component can be written as class component and others as functional or presentational components. However, the latest version of react can allow us to write every component in our application only with functional components. This was impossible in previous versions.
1913 |
1914 | ## Props
1915 |
1916 | ### Props in Functional Component
1917 |
1918 | In the previous section, we saw how to inject dynamic data type JSX. Now, let us see how we use dynamic data in component and also how to pass data as props.
1919 |
1920 | ```js
1921 | const title = 'Getting Started React'
1922 | const subtitle = 'JavaScript Library'
1923 | const author = {
1924 | firstName:'Asabeneh',
1925 | lastName:'Yetayeh'
1926 | }
1927 | const date = 'Feb 10, 2020'
1928 |
1929 | // Header Component
1930 | const Header = () => (
1931 |
1932 |
1933 |
{title}
1934 |
{subtitle}
1935 |
{author.firstName} {author.lastName]
1936 |
{date}
1937 |
1938 |
1939 | )
1940 | ```
1941 |
1942 | Instead of injecting data we can also pass the data as a props. React props is similar to parameters in function. React props is an object which you get instantly when you create a component.
1943 |
1944 | ```js
1945 | const title = 'Getting Started React'
1946 | const subtitle = 'JavaScript Library'
1947 | const author = {
1948 | firstName:'Asabeneh',
1949 | lastName:'Yetayeh'
1950 | }
1951 | const date = 'Feb 10, 2020'
1952 |
1953 | // Header Component
1954 | const Header = props => (
1955 |
1956 |
1964 |
1965 | )
1966 |
1967 | // The App, or the parent or the container component
1968 | // Functional Component
1969 | const App = () => (
1970 |
1971 |
1977 |
1978 |
1979 |
1980 | )
1981 | ```
1982 |
1983 | As you can see in the above code, the data passed as props to Header component.
1984 | [Live on code pen](https://codepen.io/Asabeneh/full/abOvEjr)
1985 |
1986 | ```html
1987 |
1988 |
1989 |
1990 |
1991 |
1992 |
1996 |
1997 | React For Everyone
1998 |
2078 |
2079 |
2080 |
2081 |
2082 |
2083 |
2087 |
2091 |
2092 |
2166 |
2167 |
2168 | ```
2169 |
2170 | #### propTypes
2171 |
2172 | So far, we are using CDN. After few lesson, we will use create-react-app to create a react project and we will start using importing packages instead of CDN. We will cover propTypes and defaultProps when we start create-react-app.
2173 |
2174 | #### defaultProps
2175 |
2176 | The defaultProps can be used when we want to have some default prop types for a component.
2177 |
2178 | #### Destructuring props
2179 |
2180 | Destructuring code to some extent makes easy to read. Let us destructure the props in Header component. Everything we passed a props is stored in props object. Therefore, props is an object and we can destructure the properties.
2181 |
2182 | ```js
2183 | // Header Component
2184 | const Header = (props) => (
2185 | const {title, subtitle, author, date} = props
2186 |
2187 |
2188 |
{title}
2189 |
{subtitle}
2190 |
{author.firstName} {author.lastName}
2191 |
{date}
2192 |
2193 |
2194 | )
2195 | ```
2196 |
2197 | Some developer prefer the above destructuring but I and most prefer the following:
2198 |
2199 | ```js
2200 | // Header Component
2201 | const Header = ({title, subtitle, author, date}) => (
2202 |
2203 |
2204 |
{title}
2205 |
{subtitle}
2206 |
{author.firstName} {author.lastName}
2207 |
{date}
2208 |
2209 |
2210 | )
2211 | ```
2212 |
2213 | Let us destructure all the props in Header, TechList and Footer. See the destructure props in the following file. [Live on code pen](https://codepen.io/Asabeneh/full/RwPWxeG)
2214 |
2215 | ```html
2216 |
2217 |
2218 |
2219 |
2220 |
2221 |
2222 |
2225 |
2226 | React For Everyone
2227 |
2307 |
2308 |
2309 |
2310 |
2311 |
2312 |
2315 |
2318 |
2319 |
2389 |
2390 |
2391 | ```
2392 |
2393 | As you can see, all the variables are declared global but most of the cases your data comes from the parent or container component. Let us move all the data to the parent component which is App. [Live on code pen](https://codepen.io/Asabeneh/full/JjdXMjp)
2394 |
2395 | ```html
2396 |
2397 |
2398 |
2399 |
2400 |
2401 |
2402 |
2405 |
2406 | React For Everyone
2407 |
2487 |
2488 |
2489 |
2490 |
2491 |
2492 |
2495 |
2498 |
2499 |
2572 |
2573 |
2574 |
2575 | ```
2576 |
2577 | ### Props in Class Components
2578 |
2579 | We access the props object in class full components using the word *this*. [Live on code pen](https://codepen.io/Asabeneh/full/poJNjjV)
2580 |
2581 | ```html
2582 |
2583 |
2584 |
2585 |
2586 |
2587 |
2588 |
2591 |
2592 | React For Everyone
2593 |
2673 |
2674 |
2675 |
2676 |
2677 |
2678 |
2681 |
2684 |
2685 |
2777 |
2778 |
2779 |
2780 | ```
2781 |
2782 | ### Rendering lists
2783 |
2784 | 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.
2785 |
2786 | In the following example, you will see how we render a number array, a string array, a countries array and skills array on the browser.
2787 |
2788 | First let us start with an array of numbers:
2789 | [Live on code pen](https://codepen.io/Asabeneh/full/QWbGbQp)
2790 |
2791 | ```html
2792 |
2793 |
2794 |
2795 |
2796 |
2797 |
2798 |
2801 | React For Everyone
2802 |
2811 |
2812 |
2813 |
2814 |
2815 |
2816 |
2819 |
2822 |
2823 |
2843 |
2844 |
2845 |
2846 | ```
2847 |
2848 | Let render more lists
2849 |
2850 | [Live on code pen](https://codepen.io/Asabeneh/full/XWbNbEY)
2851 |
2852 | ```html
2853 |
2854 |
2855 |
2856 |
2857 |
2858 |
2859 |
2862 | React For Everyone
2863 |
2872 |
2873 |
2874 |
2875 |
2876 |
2877 |
2880 |
2883 |
2884 |
2920 |
2921 |
2922 | ```
2923 |
2924 | 
2925 |
2926 | After this, we will use the *create-react-app* package to start a react project. The *create-react-app* is the standard way to create your react project.
2927 |
2928 | By now you should be familiar with:
2929 |
2930 | - JSX
2931 | - JSX Element
2932 | - Injected Dynamic data to JSX
2933 | - Babel
2934 | - React Component
2935 | - Props
2936 | - Passing props to components
2937 | - Rendering list
2938 | - Functional Component
2939 | - Class Based Component
2940 |
2941 | ## Creating a react project
2942 |
2943 | From now, on we use the *create-react-app* to create react project.
2944 | First check if you have node on your machine by typing *node* on your terminal or windows command prompt.
2945 |
2946 | ```sh
2947 | asabeneh $ node -v
2948 | v12.14.0
2949 | ```
2950 |
2951 | To create the react project you go to any directory you want your project to be and then type the following:
2952 |
2953 | ```sh
2954 | asabeneh $ nxp create-react-app name-of-your-project
2955 | ```
2956 |
2957 | After the project is created, write the following command
2958 |
2959 | ```sh
2960 | asabeneh $ nxp create-react-app name-of-your-project
2961 | asabeneh $ npm start
2962 | ```
2963 |
2964 | In other way, you can use just create-react-app followed by name of a project by installing create-react-app globally
2965 |
2966 | ```sh
2967 | asabeneh $ npm install create-react-app -g
2968 | asabeneh $ create-react-app name-of-your-project
2969 | asabeneh $ cd name-of-your-project
2970 | asabeneh $ npm start
2971 | ```
2972 |
2973 | Now, let create a react project name react-for-everyone
2974 |
2975 | ```sh
2976 | asabeneh $ npx create-react-app first-react-app
2977 | asabeneh $ cd first-react-app
2978 | asabeneh $ npm start
2979 | ```
2980 |
2981 | Now, your application is running at port 3000.
2982 |
2983 | Let us open the file on vscode and let us the files and directories.
2984 |
2985 | 
2986 |
2987 | Let us remove the unnecessary files and create components directory, after removing you will left with following structure. All the components goes to the components folder.
2988 |
2989 | 
2990 |
2991 | First modify the App.js file and run the application using npm start will launch the app on the browser. You will get the folder structure in the [*react-starter*](https://github.com/Asabeneh/React-For-Everyone/tree/master/react-starter) folder.
2992 |
2993 | 
2994 |
2995 | Now, lets create Header.js, Main.js, Footer.js component inside the components directory and move all the components we created in the previous section to their corresponding component file. And all the CSS to App.css fille. Finally, you will get this. You will get the code on [first-react-app](https://github.com/Asabeneh/React-For-Everyone/tree/master/first-react-app) folder.
2996 |
2997 | 
2998 |
2999 | We developed a very simple react application but this application can be changed to a portfolio or a blog.
3000 |
3001 | ## Events
3002 |
3003 | Let us talk about events. Let see first the most common HTML element events:
3004 | - onclick
3005 | - ondblclick
3006 | - onmouseenter
3007 | - onmousemove
3008 | - onhover
3009 | - onkeyup
3010 | - onkeydown
3011 | - onkeypress
3012 | - oninput
3013 | - onblur
3014 | - onfocus
3015 | - onchange
3016 |
3017 | In react, we can use the same events a bit differently. The HTML events will be camel case in react that means onclick will be onClick and we use the curly bracket to call the function inside the event handler.
3018 |
3019 | ```js
3020 | const App = () => {
3021 | return (
3022 |
3023 |
3024 |
3025 | )
3026 | }
3027 | ```
3028 |
3029 | Now, you attached a click event listener to the button and it should pop up an alert message. It is common to write the function outside the curly bracket. Let us take out and write it outside.
3030 |
3031 | ```js
3032 | const App = () => {
3033 | const doSomething = () => {
3034 | alert('You clicked me. Of course, I am doing something')
3035 | }
3036 | return (
3037 |
3038 |
3039 |
3040 | )
3041 | }
3042 | ```
3043 |
3044 | How about if the component is a class based component ? Lets change the above functional component and add event to the button.
3045 |
3046 | We need the *this* key word to bind the *doSomething* method to the component and the method should be an arrow function to avoid unnecessary steps of bind..
3047 |
3048 | ```js
3049 | class App extends React.Component {
3050 | doSomething = () => {
3051 | alert('You clicked me. Of course, I am doing something')
3052 | }
3053 | render() {
3054 | return (
3055 |
3056 |
3057 |
3058 |
3059 | )
3060 | }
3061 | }
3062 | ```
3063 |
3064 | Well done, now you know how to handle event in react and let move on to state. We will cover more events with state.
3065 |
3066 | With react hooks a functional component can have a state but if we do not react hooks we get state only from class components. We will learn about react hooks in the later section.
3067 |
3068 | ## State
3069 |
3070 | What is state ? The English meaning of state is *the particular condition that someone or something is in at a specific time*.
3071 |
3072 | Let us see some states being something
3073 | - Are you happy or sad?
3074 | - Is light on or off ? Is present or absent ?
3075 | - Is full or empty ?
3076 |
3077 | State is an object in react which let the component re-render when data changes. We do not directly change or mutate the state but we use the *setState()* method. As you can see below in the state object we have count with initial value 0. We can access the state object using *this.state* and the property name. See the example below.
3078 |
3079 | ```js
3080 | class App extends React.Component {
3081 | // declaring state
3082 | state = {
3083 | count: 0
3084 | }
3085 | render() {
3086 | // accessing the state value
3087 | const count = this.state.count
3088 | return (
3089 |
3090 |
{count}
3091 |
3092 | )
3093 | }
3094 | }
3095 | ```
3096 |
3097 | Now, let add some methods which increase or decrease the value of count by clicking a button. Let us add a button to increase and a button to decrease the value of count. To set the state we use react method *this.setState*. See the example below
3098 |
3099 | ```js
3100 | class App extends React.Component {
3101 | // declaring state
3102 | state = {
3103 | count: 0
3104 | }
3105 | render() {
3106 | // accessing the state value
3107 | const count = this.state.count
3108 | return (
3109 |
3110 |
{count}
3111 |
3114 |
3115 | )
3116 | }
3117 | }
3118 | ```
3119 |
3120 | If you understand the above example, adding minus one will be easy. Let us add the minus one event.
3121 |
3122 | ```js
3123 | class App extends React.Component {
3124 | // declaring state
3125 | state = {
3126 | count: 0
3127 | }
3128 | render() {
3129 | // accessing the state value
3130 | const count = this.state.count
3131 | return (
3132 |
3133 |
{count}
3134 |
3135 |
3136 | {' '}
3141 |
3146 |
3147 |
3148 | )
3149 | }
3150 | }
3151 | ```
3152 |
3153 | Both button work well, but we need to re-structure the code well. Let us create separate methods in component.
3154 | If you want to see it live check it [here][https://codepen.io/Asabeneh/full/JjdWYom]
3155 |
3156 | ```js
3157 | class App extends React.Component {
3158 | // declaring state
3159 | state = {
3160 | count: 0
3161 | }
3162 | // method which add one to the state
3163 |
3164 | addOne = () => {
3165 | this.setState({ count: this.state.count + 1 })
3166 | }
3167 |
3168 | // method which subtract one to the state
3169 | minusOne = () => {
3170 | this.setState({ count: this.state.count - 1 })
3171 | }
3172 | render() {
3173 | // accessing the state value
3174 | const count = this.state.count
3175 | return (
3176 |
3177 |
{count}
3178 |
3179 |
3180 | {' '}
3183 |
3186 |
3187 |
3188 | )
3189 | }
3190 | }
3191 | ```
3192 |
3193 | Let us do more example about state, in the following example we will develop small application which shows either a dog or cat.
3194 | We can start by setting the initial state with cat then when it is clicked it will show dog and alternatively. We need one method which changes the animal alternatively. See the code below. If you want to see live click [here](https://codepen.io/Asabeneh/full/LYVxKpq).
3195 |
3196 | ```js
3197 | class App extends React.Component {
3198 | // declaring state
3199 | state = {
3200 | image: 'https://www.smithsstationah.com/imagebank/eVetSites/Feline/01.jpg'
3201 | }
3202 | changeAnimal = () => {
3203 | let dogURL =
3204 | 'https://static.onecms.io/wp-content/uploads/sites/12/2015/04/dogs-pembroke-welsh-corgi-400x400.jpg'
3205 | let catURL =
3206 | 'https://www.smithsstationah.com/imagebank/eVetSites/Feline/01.jpg'
3207 | let image = this.state.image === catURL ? dogURL : catURL
3208 | this.setState({ image })
3209 | }
3210 |
3211 | render() {
3212 | // accessing the state value
3213 | const count = this.state.count
3214 | return (
3215 |
3216 |
React for Everyone
3217 |
3218 |
3219 |
3220 |
3221 |
3224 |
3225 | )
3226 | }
3227 | }
3228 | ```
3229 |
3230 | I believe now you have a very good understanding of state. After this, we will use state in other sections too because state and props is the core of a react application.
3231 |
3232 | ## Controlled input
3233 |
3234 | 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)
3235 |
3236 | ```js
3237 | class App extends React.Component {
3238 | // declaring state
3239 | // initial state
3240 | state = {
3241 | firstName: ''
3242 | }
3243 | handleChange = e => {
3244 | const value = e.target.value
3245 | this.setState({ firstName: value })
3246 | }
3247 |
3248 | render() {
3249 | // accessing the state value and this value will injected to the input in the value attribute
3250 | const firstName = this.state.firstName
3251 | return (
3252 |
3253 |
3260 |
{this.state.firstName}
3261 |
3262 | )
3263 | }
3264 | }
3265 | ```
3266 |
3267 | We usually use form to handle use information. Let us move to form section and make use the form element.
3268 |
3269 | ## Forms
3270 |
3271 | Form is used to collect data from user. 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).
3272 |
3273 | ```js
3274 | class App extends React.Component {
3275 | // declaring state
3276 | state = {
3277 | firstName: '',
3278 | lastName: '',
3279 | country: '',
3280 | title: ''
3281 | }
3282 | handleChange = e => {
3283 | /*
3284 | // we can get the name and value like this but we can also destructure it from e.target
3285 | const name = e.target.name
3286 | const value = e.target.value
3287 | */
3288 | const { name, value } = e.target
3289 | // [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
3290 | this.setState({ [name]: value })
3291 | }
3292 | handleSubmit = e => {
3293 | // stops the default behavior of form element specifically refreshing of page
3294 | e.preventDefault()
3295 | console.log(this.state)
3296 | }
3297 |
3298 | render() {
3299 | // accessing the state value by destrutcturing the state
3300 | const { firstName, lastName, title, country } = this.state
3301 | return (
3302 |