cleaning day_5

pull/29/head
Asabeneh 5 years ago
parent 38b69575b6
commit 33d2f10ef5

@ -39,13 +39,13 @@
## Props in Functional Component ## Props in Functional Component
In the previous day, we saw how to inject dynamic data types to React component JSX. Now, let us see how we use dynamic data in component and also how to pass data as props. In the previous day, we saw how to inject different data types to React component JSX. Now, let us see how we use it in component and also how to pass different data as props.
## What is props? ## What is props?
Props is a special keyword in React that stands for properties and is being used to pass data from one component another and mostly from parent component to child component. Props is a special keyword in React that stands for properties and is being used to pass data from one component to another and mostly from parent component to child component. We can say props is a data carrier or a means to transport data.
I hope you are familiar with JavaScript function. Most of the time, functions with parameters are smart and they can take dynamic data likewise props is a way we pass data or parameter to a component. Let's see the deference between a function and a component. I hope you are familiar with JavaScript function. Most of the time, functions with parameters are smart and they can take dynamic data likewise props is a way we pass data or parameter to a component. Let's see the difference between a function and a component.
```js ```js
// function syntax // function syntax
@ -72,7 +72,7 @@ const User = (props) => {
</div> </div>
) )
} }
// calling or instantiating a component // calling or instantiating a component, this component has three properties and we call them props:firstName, lastName, country
<User firstName = 'Asabeneh', lastName='Yetayeh' country = 'Finland' /> <User firstName = 'Asabeneh', lastName='Yetayeh' country = 'Finland' />
``` ```
@ -104,10 +104,12 @@ const Header = () => (
) )
``` ```
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. Before that let's check what do we get in the props object. Instead of injecting data we can also pass the data as a props. React props is similar to parameters in function.
## Props object ## Props object
React props is an object which you get instantly when you create a React component. Before we pass properties to the component, let's check what do we get in the props object.
```js ```js
import React from 'react' import React from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
@ -129,6 +131,7 @@ const Header = (props) => {
</header> </header>
) )
} }
// The App, or the parent or the container component // The App, or the parent or the container component
// Functional Component // Functional Component
const App = () => { const App = () => {
@ -144,9 +147,9 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
In the above console.log(props), you would get an empty object({}). That means if you do not pass any attribute to when you instantiate the component the props will be empty otherwise it will be populated with the data you passed as attributes and the proper name of these attributes are props. In the above console.log(props), you would get an empty object({}). That means if you do not pass any attributes or properties when you instantiate the component, the props will be empty otherwise it will be populated with the data you passed as attributes and the proper name of these attributes are props.
Let's start with a simple example. In the example below, the welcome message data injected as props in the Header components. Let's start with a simple example. In the example below, the welcome string has been passed as props in the Header components.
```js ```js
import React from 'react' import React from 'react'
@ -179,7 +182,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
Now, when you do console.log(props) you should get the following object, that means all the props we passed to the Header component can be found a props object. Now, when you do console.log(props) you should get the following object, that means the welcome property we passed to the Header component can be found inside the props object.
```js ```js
{ {
@ -187,9 +190,7 @@ Now, when you do console.log(props) you should get the following object, that me
} }
``` ```
As you can see in the above code, the data passed as props to Header component. As you can see in the above code, we passed only a single props to Header component, the welcome props. A component can have one or many props. Props could be different data types. It could be a string, number, boolean, array, object or a function. We will cover different kind of props in the next sections.
A component has one or many props. Props could be a string, number, boolean, array, object or a function. We will cover differ different kind of props in this sections.
### Different data type props ### Different data type props
@ -254,7 +255,7 @@ welcome: "Welcome to 30 Days Of React"
Since you are a JavaScript ninja by now, you know what do do with this object. Since you are a JavaScript ninja by now, you know what do do with this object.
As you can see from the above example, the value of the props are written statically. However, if we want to apply some logic it is hard to implement with statically written data, so it better to use a variable as props. Let's see the following example: As you can see from the above example, the value of the props are written statically. However, if we want to apply some logic it is hard to implement with statically written data, so it will be better to use a variable as props. Let's see the following example:
```js ```js
import React from 'react' import React from 'react'
@ -356,7 +357,7 @@ const Status = (props) => {
const App = () => { const App = () => {
let currentYear = 2020 let currentYear = 2020
let birthYear = 2015 let birthYear = 2015
const age = currentYear - birthYear // 200 years const age = currentYear - birthYear // 15 years
let status = age >= 18 let status = age >= 18
@ -513,7 +514,7 @@ const App = () => {
firstName: 'Asabeneh', firstName: 'Asabeneh',
lastName: 'Yetayeh', lastName: 'Yetayeh',
}, },
date: new Date(), date: new Date(), // date needs to be formatted to a human readable format
} }
return ( return (
@ -527,7 +528,7 @@ const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement) ReactDOM.render(<App />, rootElement)
``` ```
When we use object as props we usually destructure the data to access the values. Destructuring make our code easy to read. We will see soon destructuring of props but before that let's see function as a props for a React component. When we use object as props we usually destructure the data to access the values. Destructuring makes our code easy to read. We will see soon destructuring of props but before that let's see function as a props for a React component.
### Function prop types ### Function prop types
@ -537,28 +538,57 @@ We can pass function as prop type to a React component. Let's see examples
import React from 'react' import React from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
// Function to display time in Mon date, year format eg Oct 4, 2020 // A button component
const showDate = (time) => {
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]
const month = months[time.getMonth()].slice(0, 3) const Button = (props) => <button onClick={props.onClick}>{props.text}</button>
const year = time.getFullYear()
const date = time.getDate() // The App, or the parent or the container component
return ` ${month} ${date}, ${year}` // Functional Component
const App = () => {
const sayHi = () => {
alert('Hi')
}
return (
<div className='app'>
<Button text='Say Hi' onClick={sayHi} />
</div>
)
} }
const rootElement = document.getElementById('root')
// we render the JSX element using the ReactDOM package
ReactDOM.render(<App />, rootElement)
```
Even we can write function inside the curly bracket
```js
import React from 'react'
import ReactDOM from 'react-dom'
// A button component
const Button = (props) => <button onClick={props.onClick}>{props.text}</button>
// The App, or the parent or the container component
// Functional Component
const App = () => {
return (
<div className='app'>
<Button text='Say Hi' onClick={() => alert('Hi')} />
</div>
)
}
const rootElement = document.getElementById('root')
// we render the JSX element using the ReactDOM package
ReactDOM.render(<App />, rootElement)
```
Now, lets implement different functions as a props
```js
import React from 'react'
import ReactDOM from 'react-dom'
// A button component // A button component
@ -574,6 +604,7 @@ const App = () => {
return ( return (
<div className='app'> <div className='app'>
<Button text='Greet People' onClick={greetPeople} /> <Button text='Greet People' onClick={greetPeople} />
<Button text='Show Time' onClick={() => alert(new Date())} />
</div> </div>
) )
} }
@ -625,10 +656,13 @@ const App = () => {
const handleTime = () => { const handleTime = () => {
alert(showDate(new Date())) alert(showDate(new Date()))
} }
const greetPeople = () => {
alert('Welcome to 30 Days Of React Challenge, 2020')
}
return ( return (
<div className='app'> <div className='app'>
<Button text='show time' onClick={handleTime} /> <Button text='show time' onClick={handleTime} />
<Button text='Greet People' onClick={greetPeople} />
</div> </div>
) )
} }
@ -869,7 +903,7 @@ ReactDOM.render(<App />, rootElement)
``` ```
Now, let's destructure all the components we had and assemble them together. We pass props from one component to another typically from parent to a child component. Now, let's destructure all the components we had and assemble them together. We pass props from one component to another typically from parent to a child component.
For instance in the Main component techs and user props have been passed from the parent component Main to child components TechList and UserCard. Below, you will get all the codes destructured and cleaned. For instance in the Main component techs, user, greetPeople and handleTime props have been passed from the parent component Main to child components TechList and UserCard. Below, you will get all the codes destructured and cleaned.
```js ```js
import React from 'react' import React from 'react'
@ -943,7 +977,7 @@ const UserCard = ({ user: { firstName, lastName, image } }) => (
) )
// Main Component // Main Component
const Main = ({ user, techs }) => ( const Main = ({ user, techs, greetPeople, handleTime }) => (
<main> <main>
<div className='main-wrapper'> <div className='main-wrapper'>
<p>Prerequisite to get started react.js:</p> <p>Prerequisite to get started react.js:</p>
@ -951,6 +985,8 @@ const Main = ({ user, techs }) => (
<TechList techs={techs} /> <TechList techs={techs} />
</ul> </ul>
<UserCard user={user} /> <UserCard user={user} />
<Button text='Greet People' onClick={greetPeople} />
<Button text='Show Time' onClick={handleTime} />
</div> </div>
</main> </main>
) )
@ -982,10 +1018,22 @@ const App = () => {
// copying the author from data object to user variable using spread operator // copying the author from data object to user variable using spread operator
const user = { ...data.author, image: asabenehImage } const user = { ...data.author, image: asabenehImage }
const handleTime = () => {
alert(showDate(new Date()))
}
const greetPeople = () => {
alert('Welcome to 30 Days Of React Challenge, 2020')
}
return ( return (
<div className='app'> <div className='app'>
<Header data={data} /> <Header data={data} />
<Main user={user} techs={techs} /> <Main
user={user}
techs={techs}
handleTime={handleTime}
greetPeople={greetPeople}
/>
<Footer copyRight={date} /> <Footer copyRight={date} />
</div> </div>
) )

@ -68,8 +68,12 @@ const UserCard = ({ user: { firstName, lastName, image } }) => (
</div> </div>
) )
// A button component
const Button = ({ text, onClick }) => <button onClick={onClick}>{text}</button>
// Main Component // Main Component
const Main = ({ user, techs }) => ( const Main = ({ user, techs, greetPeople, handleTime }) => (
<main> <main>
<div className='main-wrapper'> <div className='main-wrapper'>
<p>Prerequisite to get started react.js:</p> <p>Prerequisite to get started react.js:</p>
@ -77,6 +81,8 @@ const Main = ({ user, techs }) => (
<TechList techs={techs} /> <TechList techs={techs} />
</ul> </ul>
<UserCard user={user} /> <UserCard user={user} />
<Button text='Greet People' onClick={greetPeople} />
<Button text='Show Time' onClick={handleTime} />
</div> </div>
</main> </main>
) )
@ -101,17 +107,29 @@ const App = () => {
firstName: 'Asabeneh', firstName: 'Asabeneh',
lastName: 'Yetayeh', lastName: 'Yetayeh',
}, },
date: new Date(), date: new Date(), // date needs to be formatted to a human readable format
} }
const date = new Date() const date = new Date()
const techs = ['HTML', 'CSS', 'JavaScript'] const techs = ['HTML', 'CSS', 'JavaScript']
// copying the author from data object to user variable using spread operator // copying the author from data object to user variable using spread operator
const user = { ...data.author, image: asabenehImage } const user = { ...data.author, image: asabenehImage }
const handleTime = () => {
alert(showDate(new Date()))
}
const greetPeople = () => {
alert('Welcome to 30 Days Of React Challenge, 2020')
}
return ( return (
<div className='app'> <div className='app'>
<Header data={data} /> <Header data={data} />
<Main user={user} techs={techs} /> <Main
user={user}
techs={techs}
handleTime={handleTime}
greetPeople={greetPeople}
/>
<Footer copyRight={date} /> <Footer copyRight={date} />
</div> </div>
) )

Loading…
Cancel
Save