Merge pull request #3 from Asabeneh/master

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

1
.gitignore vendored

@ -1,7 +1,6 @@
draft.md draft.md
react-for-everyone.md react-for-everyone.md
component.md component.md
09_Day_Conditional_Rendering
10_Day_Events 10_Day_Events
11_Day_Forms 11_Day_Forms

@ -324,7 +324,7 @@ An array is a collection of different data types which are ordered and changeabl
#### How to create an empty array #### How to create an empty array
In JavaScript, we can create an array in different ways. Let us see different ways to create an array. In JavaScript, we can create an array in different ways. Let us see different ways to create an array.
It is very common to use _const_ instead of _let_ to declare an array variable. If you ar using const it means you do not use that variable name again. It is very common to use _const_ instead of _let_ to declare an array variable. If you are using const it means you do not use that variable name again.
- Using Array constructor - Using Array constructor

@ -39,13 +39,13 @@
# Setting Up # Setting Up
In the previous section, we learned about JSX and we accessed the React and ReactDOM package using CDN. However, in real projects instead of CDN you will use the create-react-app package to generate a React project starter(boilerplate). The initial _create-react-app_ was released on Jul 22, 2016. Before this time, developers used to configure webpack which a JavaScript module bundler, babel and all the necessary packages manually and this used to take half an hour or may be more. Now, create-react-app will take care of everything and you will be in charge of developing the product only instead of spending too much time configuring and setting up projects. Before we start using different tools, let's have a brief introduction for all the tools we are going to use in this challenge. You do not have to understand everything but I will try to give a very short introduction about some of the tools and technologies which we use when we work with React. In the previous section, we learned about JSX and we accessed the React and ReactDOM package using CDN. However, in real projects instead of CDN you will use the create-react-app package to generate a React project starter(boilerplate). The initial _create-react-app_ was released on Jul 22, 2016. Before this time, developers used to configure webpack with a JavaScript module bundler, babel and all the necessary packages manually and this used to take half an hour or maybe more. Now, create-react-app will take care of everything and you will be in charge of only developing the product, instead of spending too much time configuring and setting up projects. Before we start using different tools, let's have a brief introduction to all the tools we are going to use in this challenge. You do not have to understand everything, but I will try to give a very short introduction to some of the tools and technologies that we use when we work with React.
## Node ## Node
Node is a JavaScript runtime environment which allows JavaScript to run on the server. Node was created in 2009. Node has played a great role for the growth of JavaScript. The React application starts by default at localhost 3000. The create-react-app has configured a node server for the React Application. That is why we need node and node modules. We will see create-react-app soon. Node is a JavaScript runtime environment that allows JavaScript to run on the server. Node was created in 2009. Node has played a great role for the growth of JavaScript. The React application starts by default at localhost 3000. The create-react-app has configured a node server for the React Application. That is why we need node and node modules. We will see create-react-app soon.
If you do have node, install node. Install [node.js](https://nodejs.org/en/). If you do not have node, install it. Install [node.js](https://nodejs.org/en/).
![Node download](../images/download_node.png) ![Node download](../images/download_node.png)
@ -53,7 +53,7 @@ After downloading double click and install
![Install node](../images/install_node.png) ![Install node](../images/install_node.png)
We can check if node is installed on our local machine by opening our device terminal or command prompt and writing the following command. We can check if node is installed on our local machine, by opening our device terminal or command prompt, and writing the following command:
```sh ```sh
asabeneh $ node -v asabeneh $ node -v
@ -62,8 +62,8 @@ v12.18.0
## Module ## Module
A single or multiple functions which can be exported and imported when needed and can be included in a project. A single or multiple functions, that can be exported and imported when needed, can be included in a project.
In react we do not use link to access modules or packages instead we import the module. Let's see how to import and export a module or modules In React we do not use link to access modules or packages, instead we import the module. Let's see how to import and export a module or modules:
```js ```js
// math.js // math.js
@ -80,7 +80,7 @@ export default (function doSomeMath() {
})() })()
``` ```
Now let's import the _math.js_ modules to a different file. Now let's import the _math.js_ modules to a different file:
```js ```js
// index.js // index.js
@ -91,7 +91,7 @@ import doSomeMath from './math.js'
// since these modules were not exported as default we have to desctructure // since these modules were not exported as default we have to desctructure
import { addTwo, multiply, subtract } from './math.js' import { addTwo, multiply, subtract } from './math.js'
import * as everything from './math.js' // to import everything renaming import * as everything from './math.js' // to import everything remaining
console.log(addTwo(5, 5)) console.log(addTwo(5, 5))
console.log(doSomeMath.addTwo(5, 5)) console.log(doSomeMath.addTwo(5, 5))
console.log(everything) console.log(everything)
@ -105,17 +105,17 @@ A Package is a module or a collection of modules. For instance, React, ReactDOM
## Node Package Manager(NPM) ## Node Package Manager(NPM)
NPM was created in 2010. You do not need to install NPM separately when you install node you will have also NPM. NPM is a default package manager for Node.js. It allows users to consume and distribute JavaScript modules that are available in the registry. NPM allows to create packages, use packages and distribute packages. NMP has also play quite a big role in the growth of JavaScript. Currently, there is more than 350, 000 package on NPM registry. Let's see the create-react-app on NPM registry. The number of downloads show the popularity of the package. NPM was created in 2010. You do not need to install NPM separately - when you install node you will have also NPM. NPM is a default package manager for Node.js. It allows users to consume and distribute JavaScript modules that are available in the registry. NPM allows to create packages, use packages and distribute packages. NMP also played quite a big role in the growth of JavaScript. Currently, there is more than 350,000 packages in the NPM registry. Let's see the create-react-app on NPM registry. The number of downloads show the popularity of the package.
![NPM create-react-app](../images/npm_registry.png) ![NPM create-react-app](../images/npm_registry.png)
## Visual Studio Code ## Visual Studio Code
We will use Visual Studio Code as a code editor and [download](https://code.visualstudio.com) and install it if you do not have one yet. We will use Visual Studio Code as a code editor. [Download](https://code.visualstudio.com) and install it if you do not have one yet.
## Browser ## Browser
We will use Google chrome We will use Google Chrome
## Visual Studio Extensions ## Visual Studio Extensions
@ -128,7 +128,7 @@ You may need to install these extensions from Visual Studio Code
## Create React App ## Create React App
To create a react project you can use one of the following ways. Let's assume you installed node. Open the command line interface , git bash or terminal on Mac or Linux. Then run the following command. I am using git bash. To create a react project you can use one of the following ways. Let's assume you installed node. Open the command line interface (CLI), git bash or terminal on Mac or Linux. Then run the following command. I am using git bash.
```sh ```sh
Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop
@ -142,7 +142,7 @@ Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop
$ npm install -g create-react-app $ npm install -g create-react-app
``` ```
After you installed create-react app, you create a React application as follows: After you installed create-react-app, you create a React application as follows:
```sh ```sh
Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop
@ -171,51 +171,52 @@ Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop/30-days-of-react (master)
\$ npm start \$ npm start
``` ```
Now your react app should run at localhost 3000. Go to the App.js and modify the content by writing some text, you will see the latest change on the browsers. Now your React app should run at localhost 3000. Go to the App.js and modify the content by writing some text, you will see the latest changes on the browser.
To stop the running server, press Ctr + C To stop the server, press Ctr + C in the CLI.
![React Starting](../images/react_app_starting.png) ![React Starting](../images/react_app_starting.png)
## React Boilerplate ## React Boilerplate
Let's see the React boilerplate which has been created by create-react-app. Whenever you create a new project you run create-react-app and name of the project. Let's see the React boilerplate, which has been created by create-react-app. Whenever you create a new project, you run create-react-app and name of the project.
In the following React boilerplate, there are three folders:node_modules, public and src. In addition, there are .gitignore, README.mde, package.json and yarn.lock. In some of you instead of yarn.lock, you may have package-lock.json. In the following React boilerplate, there are three folders: node_modules, public and src. In addition, there are .gitignore, README.md, package.json and yarn.lock. Some of you, instead of yarn.lock, you may have package-lock.json.
It is good to know these folders and files. It is good to know these folders and files.
- node_modules - store all the necessary node packages of the react applications. - node_modules - stores all the necessary node packages of the React applications.
- Public - Public
-index.html - the only HTML file we have in the entire application
- favicon.io - a favicon - index.html - the only HTML file we have in the entire application
- manifest.json - is use to make the application a progressive web app
- other images- which can be used for open graph image or for other purposes - favicon.ico - an icon file
- robots.txt - information if the website allow web scraping - manifest.json - is used to make the application a progressive web app
- other images - open graph images(open graph images are images which are visible when a link share on social media)
- robots.txt - information, if the website allows web scraping
- src - src
- App.css, index.css - are different CSS files - App.css, index.css - are different CSS files
- index.js - a file which allows to connect all the components with index.html - index.js - a file which allows to connect all the components with index.html
- App.js - A file which we import most the presentational components - App.js - A file where we usually import most of the presentational components
- serviceWorker.js: is used to add progressive web app feature - serviceWorker.js: is used to add progressive web app features
- setupTests.js - to write testing cases - setupTests.js - to write testing cases
- package.json- List of packages the applications uses - package.json- List of packages the applications uses
- .gitignore - React boilerplate comes with git initiated, and the .gitingore allow files and folders not to be pushed to GitHub - .gitignore - React boilerplate comes with git initiated, and the .gitingore allows files and folders not to be pushed to GitHub
- README.md - Markdown file to write documentation - README.md - Markdown file to write documentation
- yarn.lock or package-lock.json - a means to lock the version of the package - yarn.lock or package-lock.json - a means to lock the version of the package
![React Boilerplate](../images/react_boilerplate.png) ![React Boilerplate](../images/react_boilerplate.png)
Now lets remove all the file which we do not need at the moment and leave only the file we need right now. Now lets remove all the files, which we do not need at the moment, and leave only the files we need right now.
After removing most of the file, the structure of the boilerplate looks like this: After removing most of the files, the structure of the boilerplate looks like this:
![React Boilerplate Cleaned](../images/react_bolier_plate_cleaned.png) ![React Boilerplate Cleaned](../images/react_bolier_plate_cleaned.png)
Now lets write code on index.js. First of we should import React and ReactDOM. React allows us to write JSX and ReactDOM to render the JSX on the DOM. ReactDOM has render method. Let's use all the JSX elements we created on Day 2. The ReactDOM render method takes two parameters a JSX or a component and the root. Now lets write code on index.js. First of, we should import React and ReactDOM. React allows us to write JSX and ReactDOM to render the JSX on the DOM. ReactDOM has a render method. Let's use all the JSX elements we created on Day 2. The ReactDOM render method takes two parameters, a JSX or a component and the root.
```js ```js
//index.js //index.js
@ -261,7 +262,7 @@ Asabeneh@DESKTOP-KGC1AKC MINGW64 ~/Desktop/30-days-of-react (master)
\$ npm start \$ npm start
``` ```
If you do not have any bugs your React app will be launched on the browser. If you do not have any bugs, your React app will be launched on the browser.
![JSX using create react app](../images/jsx_use_create_react_app.png) ![JSX using create react app](../images/jsx_use_create_react_app.png)
@ -271,7 +272,7 @@ Let's write more JSX elements and render them on the browser. This expression is
const title = <h2>Getting Started React</h2> const title = <h2>Getting Started React</h2>
``` ```
Let's add more content the previous JSX and change the name to header. Let's add more content to the previous JSX and change the name to header.
```js ```js
const header = ( const header = (
@ -283,7 +284,7 @@ const header = (
) )
``` ```
Let's render this to the browser, in order to render we need ReactDOM. Let's render this to the browser, in order to do so, we need ReactDOM.
```js ```js
//index.js //index.js
@ -367,7 +368,7 @@ ReactDOM.render(app, rootElement)
## Styles in JSX ## Styles in JSX
Let's apply style to the JSX elements. We can style JSX either using inline, internal or external CSS styles. Now, let's apply an inline styles to each JSX elements. Let's apply style to the JSX elements. We can style JSX either using inline, internal or external CSS styles. Now, let's apply inline styles to each JSX element.
```js ```js
// index.js // index.js
@ -435,7 +436,7 @@ ReactDOM.render(app, rootElement)
![Inline styling JSX](../images/styling_jsx_inline_create_react_app.png) ![Inline styling JSX](../images/styling_jsx_inline_create_react_app.png)
Now, lets apply an internal style, we put all the CSS on the header of the index.html. Now, lets apply an internal style, we put all the CSS in the header of the index.html.
```js ```js
// index.js // index.js
@ -602,8 +603,8 @@ ReactDOM.render(app, rootElement)
## Importing Media Objects in React ## Importing Media Objects in React
How do we import images, video and audio in react? Let's see how we import image first. How do we import images, video and audio in React? Let's see how we import images first.
Create images folder in the src folder and save an image. For instance let's save asabeneh.jpg image and let's import this image to index.js. After importing we will inject it to a JSX expression, user. See the code below. Create images folder in the src folder and save an image inside. For instance let's save asabeneh.jpg image and let's import this image to index.js. After importing we will inject it to a JSX expression, user. See the code below.
```js ```js
// index.js // index.js
@ -624,7 +625,7 @@ ReactDOM.render(user, rootElement)
![Rendering image](../images/rendering_image.png) ![Rendering image](../images/rendering_image.png)
Let's inject the user inside the main JSX element and see the result Let's inject the user inside the main JSX element and see the result:
```js ```js
// index.js // index.js
@ -738,27 +739,27 @@ The boilerplate code can be found [here](../03/../03_Day_Setting_Up/30-days-of-r
## Exercises: Level 1 ## Exercises: Level 1
1. What is module 1. What is a module?
2. What is package ? 2. What is package?
3. What is the difference between a module and a package 3. What is the difference between a module and a package.
4. What is NPM ? 4. What is NPM?
5. What is Webpack ? 5. What is Webpack?
6. How do you create a new React project ? 6. How do you create a new React project?
7. What are these files and folders in a project(package.json, package-lock.json or yarn.lock, .gitignore,node_modules and public ) 7. What are the files and folders inside a project folder(package.json, package-lock.json or yarn.lock, .gitignore,node_modules and public)?
8. What is your favorite code editor (I believe that it is Visual Studio Code) ? 8. What is your favorite code editor (I believe that it is Visual Studio Code)?
9. Add different Visual Studio Code extensions to imporve your productivity(eg. prettier, ESLint etc) 9. Add different Visual Studio Code extensions to imporve your productivity(eg. prettier, ESLint etc).
10. 6. Try to make different module in a different file and import it to index.js. 10. Try to make a different module in a different file and import it to index.js.
## Exercises: Level 2 ## Exercises: Level 2
1. Import and render the following images 1. Import and render the following images
![Front end](../images/frontend_technologies.png) ![Front end](../images/frontend_technologies.png)
2.Design the following user card. 2. Design the following user card.
![User Card](../images/user_card_design_jsx.png) ![User Card](../images/user_card_design_jsx.png)
3. Use h1, p, input and button HTML element to create the following design using JSX 3. Use h1, p, input and button HTML elements to create the following design using JSX
![News Letter](../images/news_letter_design.png) ![News Letter](../images/news_letter_design.png)

@ -19,17 +19,27 @@
![30 Days of React banner](../images/30_days_of_react_banner_day_8.jpg) ![30 Days of React banner](../images/30_days_of_react_banner_day_8.jpg)
- [State](#state) - [State](#state)
- [What is State?](#what-is-state)
- [How to set a state](#how-to-set-a-state)
- [Resetting a state using a JavaScript method](#resetting-a-state-using-a-javascript-method)
- [Exercises](#exercises) - [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1) - [Exercises: Level 1](#exercises-level-1)
- [Exercise: Level 2](#exercise-level-2) - [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# State # State
## What is State?
What is state ? The English meaning of state is _the particular condition that someone or something is in at a specific time_. What is state ? The English meaning of state is _the particular condition that someone or something is in at a specific time_.
Let us see some states being something - Are you happy or sad? - Is light on or off ? Is present or absent ? - Is full or empty ? For instance, I am happy because I am enjoying creating 30 Days Of React challenge. I believe that you are happy too. Let us see some states being something - Are you happy or sad? - Is light on or off ? Is present or absent ? - Is full or empty ? For instance, I am happy because I am enjoying creating 30 Days Of React challenge. I believe that you are happy too.
State is an object in react which let the component re-render when 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. State is an object in react which let the component re-render when state data changes.
## How to set a state
We set an initial state inside the constructor or outside the constructor of a class based component. We do not directly change or mutate the state but we use the _setState()_ method to reset to a new state. . As you can see below in the state object we have count with initial value 0. We can access the state object using _this.state_ and the property name. See the example below.
```js ```js
// index.js // index.js
@ -57,6 +67,8 @@ ReactDOM.render(<App />, rootElement)
If you run the above code you will see zero on the browser. We can increase or decrease the value the state by changing the value of the state using JavaScript method. If you run the above code you will see zero on the browser. We can increase or decrease the value the state by changing the value of the state using JavaScript method.
## Resetting a state using a JavaScript method
Now, let's add some methods which increase or decrease the value of count by clicking a button. Let us add a button to increase and a button to decrease the value of count. To set the state we use react method _this.setState_. See the example below Now, let's add some methods which increase or decrease the value of count by clicking a button. Let us add a button to increase and a button to decrease the value of count. To set the state we use react method _this.setState_. See the example below
```js ```js
@ -124,7 +136,6 @@ ReactDOM.render(<App />, rootElement)
``` ```
Both button work well, but we need to re-structure the code well. Let us create separate methods in the component. Both button work well, but we need to re-structure the code well. Let us create separate methods in the component.
If you want to see it live check it [here][https://codepen.io/asabeneh/full/jjdwyom]
```js ```js
// index.js // index.js
@ -471,11 +482,11 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
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. I believe that now you have a very good understanding of state. After this, we will use state in other sections too because state and props is the core of a react application.
## Exercises ## Exercises
### Exercise: Level 1 ### Exercises: Level 1
1. What was your state today? Are you happy? I hope so. If you manage to make it this far you should be happy. 1. What was your state today? Are you happy? I hope so. If you manage to make it this far you should be happy.
2. What is state in React ? 2. What is state in React ?
@ -483,16 +494,20 @@ I believe now you have a very good understanding of state. After this, we will u
4. How do you access state in a React component ? 4. How do you access state in a React component ?
5. How do you set a set in a React component ? 5. How do you set a set in a React component ?
### Exercise: Level 2 ### Exercises: Level 2
1. Use React state to change the background of the page. You can use this technique to apply a dark mode for your portfolio. 1. Use React state to change the background of the page. You can use this technique to apply a dark mode for your portfolio.
![Change Background](../images/08_day_changing_background_exercise.gif) ![Change Background](../images/08_day_changing_background_exercise.gif)
2. After long time of lock down you may think of travelling and you do not know where to go. Then make use of this random country selector to select your holiday destination. 2. After long time of lock down you may think of travelling and you do not know where to go. Then make use of this random country selector to select your holiday destination.
![Change Background](../images/08_day_select_country_exercise.gif) ![Change Background](../images/08_day_select_country_exercise.gif)
### Exercises: Level 3
Coming
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 7](../07_Day_Class_Components/07_class_components.md) | [Day 9 >>](../09_Day_Conditional_Rendering/09_conditional_rendering.md) [<< Day 7](../07_Day_Class_Components/07_class_components.md) | [Day 9 >>](../09_Day_Conditional_Rendering/09_conditional_rendering.md)

@ -0,0 +1,790 @@
<div align="center">
<h1> 30 Days Of React: Conditional Rendering</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 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_Day_Events/10_events.md)
![30 Days of React banner](../images/30_days_of_react_banner_day_9.jpg)
# Conditional Rendering
As we can understand from the term, conditional rendering is a way to render different JSX or component at different condition. We can implement conditional rendering using regular if and else statement, ternary operator and &&. Let's implement a different conditional rendering.
## Conditional Rendering using If and Else statement
In the code below, we have an initial state of loggedIn which is false. If the state is false we inform user to log in otherwise we welcome the user.
```js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
// class based component
class Header extends React.Component {
render() {
console.log(this.props.data)
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = this.props.data
return (
<header style={this.props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
<p>Select a country for your next holiday</p>
</div>
</header>
)
}
}
class App extends React.Component {
state = {
loggedIn: false,
}
render() {
const data = {
welcome: '30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 7, 2020',
}
// conditional rendering using if and else statement
let status
if (this.state.loggedIn) {
status = <h3>Welcome to 30 Days Of React</h3>
} else {
status = <h3>Please Login</h3>
}
return (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
{status}
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
Let's add a method which allow as to toggle the status of the user. We should have a button to handle event for logging in and logging out.
```js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 3,
cursor: 'pointer',
fontSize: 22,
color: 'white',
margin: '0 auto',
}
// class based component
class Header extends React.Component {
render() {
console.log(this.props.data)
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = this.props.data
return (
<header style={this.props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
}
class App extends React.Component {
state = {
loggedIn: false,
}
handleLogin = () => {
this.setState({
loggedIn: !this.state.loggedIn,
})
}
render() {
const data = {
welcome: '30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 9, 2020',
}
let status
let text
if (this.state.loggedIn) {
status = <h1>Welcome to 30 Days Of React</h1>
text = 'Logout'
} else {
status = <h3>Please Login</h3>
text = 'Login'
}
return (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
{status}
<Button text={text} style={buttonStyles} onClick={this.handleLogin} />
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
How about if our condition is more than two? Like pure JavaScript we can use if else if statement. In general, conditional rendering is not different from pure JavaScript conditional statement.
## Conditional Rendering using Ternary Operator
Ternary operator is an an alternative for if else statement. However, there is more use cases for ternary operator than if else statement. For example, use can use ternary operator inside styles, className or many places in a component than regular if else statement.
```js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 3,
cursor: 'pointer',
fontSize: 22,
color: 'white',
margin: '0 auto',
}
// class based component
class Header extends React.Component {
render() {
console.log(this.props.data)
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = this.props.data
return (
<header style={this.props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
}
class App extends React.Component {
state = {
loggedIn: false,
}
handleLogin = () => {
this.setState({
loggedIn: !this.state.loggedIn,
})
}
render() {
const data = {
welcome: '30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 9, 2020',
}
let status = this.state.loggedIn ? (
<h1>Welcome to 30 Days Of React</h1>
) : (
<h3>Please Login</h3>
)
return (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
{status}
<Button
text={this.state.loggedIn ? 'Logout' : 'Login'}
style={buttonStyles}
onClick={this.handleLogin}
/>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
In addition to JSX, we can also conditionally render a component. Let's change the above conditional JSX to a component.
```js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 3,
cursor: 'pointer',
fontSize: 22,
color: 'white',
margin: '0 auto',
}
// class based component
class Header extends React.Component {
render() {
console.log(this.props.data)
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = this.props.data
return (
<header style={this.props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
}
class App extends React.Component {
state = {
loggedIn: false,
}
handleLogin = () => {
this.setState({
loggedIn: !this.state.loggedIn,
})
}
render() {
const data = {
welcome: '30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 9, 2020',
}
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div>
<h1>Welcome to 30 Days Of React</h1>
</div>
)
const status = this.state.loggedIn ? <Welcome /> : <Login />
return (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
{status}
<Button
text={this.state.loggedIn ? 'Logout' : 'Login'}
style={buttonStyles}
onClick={this.handleLogin}
/>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
## Conditional Rendering using && Operator
The && operator render the right JSX operand if the left operand(expression) is true.
```js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 3,
cursor: 'pointer',
fontSize: 22,
color: 'white',
margin: '0 auto',
}
// class based component
class Header extends React.Component {
render() {
console.log(this.props.data)
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = this.props.data
return (
<header style={this.props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
}
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div>
<h1>Welcome to 30 Days Of React</h1>
</div>
)
class App extends React.Component {
state = {
loggedIn: false,
techs: ['HTML', 'CSS', 'JS'],
}
handleLogin = () => {
this.setState({
loggedIn: !this.state.loggedIn,
})
}
render() {
const data = {
welcome: '30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 9, 2020',
}
const status = this.state.loggedIn ? <Welcome /> : <Login />
return (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
{status}
<Button
text={this.state.loggedIn ? 'Logout' : 'Login'}
style={buttonStyles}
onClick={this.handleLogin}
/>
{this.state.techs.length === 3 && (
<p>You have all the prerequisite courses to get started React</p>
)}
{!this.state.loggedIn && (
<p>
Please login to access more information about 30 Days Of React
challenge
</p>
)}
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
In the previous section, we used alert box to greet people and also to display time. Let's render the greeting and time on browser DOM instead of displaying on alert box.
```js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
// class based component
class Header extends React.Component {
render() {
console.log(this.props.data)
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = this.props.data
return (
<header style={this.props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
}
const Message = ({ message }) => (
<div>
<h1>{message}</h1>
</div>
)
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div>
<h1>Welcome to 30 Days Of React</h1>
</div>
)
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// TechList Component
// class base component
class TechList extends React.Component {
render() {
const { techs } = this.props
const techsFormatted = techs.map((tech) => <li key={tech}>{tech}</li>)
return techsFormatted
}
}
// Main Component
// Class Component
class Main extends React.Component {
render() {
const {
techs,
greetPeople,
handleTime,
loggedIn,
handleLogin,
message,
} = this.props
console.log(message)
const status = loggedIn ? <Welcome /> : <Login />
return (
<main>
<div className='main-wrapper'>
<p>Prerequisite to get started react.js:</p>
<ul>
<TechList techs={this.props.techs} />
</ul>
{techs.length === 3 && (
<p>You have all the prerequisite courses to get started React</p>
)}
<div>
<Button
text='Show Time'
onClick={handleTime}
style={buttonStyles}
/>{' '}
<Button
text='Greet People'
onClick={greetPeople}
style={buttonStyles}
/>
{!loggedIn && <p>Please login to access more information about 30 Days Of React challenge</p>}
</div>
<div style={{ margin: 30 }}>
<Button
text={loggedIn ? 'Logout' : 'Login'}
style={buttonStyles}
onClick={handleLogin}
/>
<br />
{status}
</div>
<Message message={message} />
</div>
</main>
)
}
}
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 3,
cursor: 'pointer',
fontSize: 22,
color: 'white',
margin: '0 auto',
}
// Footer Component
// Class component
class Footer extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<footer>
<div className='footer-wrapper'>
<p>Copyright {this.props.date.getFullYear()}</p>
</div>
</footer>
)
}
}
class App extends React.Component {
state = {
loggedIn: false,
techs: ['HTML', 'CSS', 'JS'],
message: 'Click show time or Greet people to change me',
}
handleLogin = () => {
this.setState({
loggedIn: !this.state.loggedIn,
})
}
showDate = (time) => {
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]
const month = months[time.getMonth()].slice(0, 3)
const year = time.getFullYear()
const date = time.getDate()
return `${month} ${date}, ${year}`
}
handleTime = () => {
let message = this.showDate(new Date())
this.setState({ message })
}
greetPeople = () => {
let message = 'Welcome to 30 Days Of React Challenge, 2020'
this.setState({ message })
}
render() {
const data = {
welcome: '30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 9, 2020',
}
const techs = ['HTML', 'CSS', 'JavaScript']
return (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
<Main
techs={techs}
handleTime={this.handleTime}
greetPeople={this.greetPeople}
loggedIn={this.state.loggedIn}
handleLogin={this.handleLogin}
message={this.state.message}
/>
<Footer date={new Date()} />
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
```
## Exercises
### Exercises: Level 1
1. What is conditional rendering?
2. How do you implement conditional rendering?
3. Which method of conditional rendering do you prefer?
### Exercises: Level 2
Coming
### Exercises: Level 3
Coming
🎉 CONGRATULATIONS ! 🎉
[<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_Day_Events/10_events.md)

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

@ -0,0 +1,5 @@
# 30 Days of React App: Day 3
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,230 @@
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
// class based component
class Header extends React.Component {
render() {
console.log(this.props.data)
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = this.props.data
return (
<header style={this.props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
}
const Message = ({ message }) => (
<div>
<h1>{message}</h1>
</div>
)
const Login = () => (
<div>
<h3>Please Login</h3>
</div>
)
const Welcome = (props) => (
<div>
<h1>Welcome to 30 Days Of React</h1>
</div>
)
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// TechList Component
// class base component
class TechList extends React.Component {
render() {
const { techs } = this.props
const techsFormatted = techs.map((tech) => <li key={tech}>{tech}</li>)
return techsFormatted
}
}
// Main Component
// Class Component
class Main extends React.Component {
render() {
const {
techs,
greetPeople,
handleTime,
loggedIn,
handleLogin,
message,
} = this.props
console.log(message)
const status = loggedIn ? <Welcome /> : <Login />
return (
<main>
<div className='main-wrapper'>
<p>Prerequisite to get started react.js:</p>
<ul>
<TechList techs={this.props.techs} />
</ul>
{techs.length === 3 && (
<p>You have all the prerequisite courses to get started React</p>
)}
<div>
<Button
text='Show Time'
onClick={handleTime}
style={buttonStyles}
/>{' '}
<Button
text='Greet People'
onClick={greetPeople}
style={buttonStyles}
/>
{!loggedIn && (
<p>
Please login to access more information about 30 Days Of React
challenge
</p>
)}
</div>
<div style={{ margin: 30 }}>
<Button
text={loggedIn ? 'Logout' : 'Login'}
style={buttonStyles}
onClick={handleLogin}
/>
<br />
{status}
</div>
<Message message={message} />
</div>
</main>
)
}
}
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 3,
cursor: 'pointer',
fontSize: 22,
color: 'white',
margin: '0 auto',
}
// Footer Component
// Class component
class Footer extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<footer>
<div className='footer-wrapper'>
<p>Copyright {this.props.date.getFullYear()}</p>
</div>
</footer>
)
}
}
class App extends React.Component {
state = {
loggedIn: false,
techs: ['HTML', 'CSS', 'JS'],
message: 'Click show time or Greet people to change me',
}
handleLogin = () => {
this.setState({
loggedIn: !this.state.loggedIn,
})
}
showDate = (time) => {
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]
const month = months[time.getMonth()].slice(0, 3)
const year = time.getFullYear()
const date = time.getDate()
return `${month} ${date}, ${year}`
}
handleTime = () => {
let message = this.showDate(new Date())
this.setState({ message })
}
greetPeople = () => {
let message = 'Welcome to 30 Days Of React Challenge, 2020'
this.setState({ message })
}
render() {
const data = {
welcome: '30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 9, 2020',
}
const techs = ['HTML', 'CSS', 'JavaScript']
return (
<div className='app'>
{this.state.backgroundColor}
<Header data={data} />
<Main
techs={techs}
handleTime={this.handleTime}
greetPeople={this.greetPeople}
loggedIn={this.state.loggedIn}
handleLogin={this.handleLogin}
message={this.state.message}
/>
<Footer date={new Date()} />
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

@ -31,7 +31,7 @@
|06|[List, Map and Keys](./06_Day_Map_List_Keys/06_map_list_keys.md)| |06|[List, Map and Keys](./06_Day_Map_List_Keys/06_map_list_keys.md)|
|07|[Class Components](./07_Day_Class_Components/07_class_components.md)| |07|[Class Components](./07_Day_Class_Components/07_class_components.md)|
|08|[States](./08_Day_States/08_states.md)| |08|[States](./08_Day_States/08_states.md)|
|09|[Conditional Rendering 😞]()| |09|[Conditional Rendering](./09_Day_Conditional_Rendering/09_conditional_rendering.md)|
|10|[Events 😞]()| |10|[Events 😞]()|
|11|[Forms 😞]()| |11|[Forms 😞]()|
|13|[Controlled and Uncondrolled Component 😞]()| |13|[Controlled and Uncondrolled Component 😞]()|
@ -282,7 +282,7 @@ Programming languages are similar to human languages. English or many other lang
I made a deliberate mistake. As a result, the console raises syntax errors. Actually, the syntax is very informative. It informs what type of mistake was made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors: I made a deliberate mistake. As a result, the console raises syntax errors. Actually, the syntax is very informative. It informs what type of mistake was made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors:
```js ```js
console.log('Hello, World!') console.log("Hello, World!")
console.log('Hello, World!') console.log('Hello, World!')
``` ```

Loading…
Cancel
Save