why it is used?
Library for JS
ReactDOM.render(what we what to render, where ?) ⟶ used in React17
ReactDOM.createRoot(document.getElementById("root")).render(navbar)
⟶ used in React18
Another way in React18 is ⟶
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(navbar)
By using this way we can perform diff operations on the root as well
What ReactDOM.render() actually do
ReactDOM.render()
is a React method to render a React app to the web page.ReactDOM.render()
takes at least 2 parameters:element (what we want to render)
container (where we want to render)
What does it mean for something to be "declarative" instead of "imperative"?
Declarative means I can tell the computer WHAT to do
and expect it to handle the details. Imperative means I need
to tell it HOW to do each step.
Create React reusable function/ reusable component
⟶ use Pascal case
function TempComponet() {
return()
}
//calling of the function should be in the same way just like a normal HTML component
ReactDOM.render(<TemporaryName />, document.getElementById("root"))
Parent and Child Components
function Header() {
return (
<header>
<nav>
<img src="./react-logo.png" width="40px" />
</nav>
</header>
)
}
function Footer() {
return (
<footer>
<small>© 2021 Ziroll development. All rights reserved.</small>
</footer>
)
}
function MainContent () {
return (
<>
<h1>Reasons I'm excited to learn React</h1>
<ol>
<li>It's a popular library, so I'll be
able to fit in with the cool kids!</li>
<li>I'm more likely to get a job as a developer
if I know React</li>
</ol>
</>
)
}
//Parent Element
function Page() {
return (
<div>
//Child Elements
<Header />
<MainContent/>
<Footer/>
</div>
)
}
ReactDOM.render(<Page />, document.getElementById("root"))
Here we are nesting components inside another component and then rendering the parent element/component at the end
We can nest any number of child components inside a parent component
Made static Websites
React Fun Facts
BusinessCard (solo project)
Business Card
Data-Driven React
JS inside JSX
we can insert JS inside the JSX element using {}
for ex:
function App() {
const firstName = "Joe"
const lastName = "Schmoe"
return (
<h1>Hello {firstName} + " " + {lastName}</h1>
)
}
In layman's language, we can say that whenever there is {} we enter the JS world and we can write normal JavaScript but whenever we are outside the {} we are in the JSX world and we have to write JSX syntax.
So we write the logic want we want to show on the screen above the return function and then embed that code inside the JSX code
for ex:
function App() {
const date = new Date()
const hours = date.getHours()
let timeOfDay
if (hours < 12) {
timeOfDay = "morning"
} else if (hours >= 12 && hours < 17) {
timeOfDay = "afternoon"
} else {
timeOfDay = "night"
}
return (
<h1>Good {timeOfDay}!</h1>
)
}
Output : based on time
Good Afternoon (If the timeOfDay is b/w 12 to 17)
Props
React Props are like function arguments in JavaScript and attributes in HTML.
Example
Add a "brand" attribute to the Car element:
const myElement = <Car brand="Ford" />;
The component receives the argument as a
props
object:Example
Use the brand attribute in the component:
function Car(props) { return <h2>I am a { props.brand }!</h2>;}
Props Quiz
What do props help us accomplish?
Make a component more reusable.
How do you pass a prop into a component?
<MyAwesomeHeader title="???" />
Can I pass a custom prop (e.g.
blahblahblah={true}
) to a nativeDOM element? (e.g. <div blahblahblah={true}>) Why or why not?
No, because the JSX we use to describe native DOM elements will
be turned into REAL DOM elements by React. And real DOM elements
only have the properties/attributes specified in the HTML specification.
(Which doesn't include properties like
blahblahblah
)How do I receive props in a component?
function Navbar(props) { console.log(props.blahblahblah) return ( <header> ... </header> ) }
What data type is
props
when the component receives it?An object!
Destructuring props :
export default function Contact({img, name, phone, email}) { return ( <div className="contact-card"> <img src={props.img}/> <h3>{props.name}</h3> <div className="info-group"> <img src="./images/phone-icon.png" /> <p>{props.phone}</p> </div> <div className="info-group"> <img src="./images/mail-icon.png" /> <p>{props.email}</p> </div> </div> ) } const person = { img: “”, phone: “”, email : “”, } cons {name, email} = person console.log(name)
Creating components from Array
Arrays.map() ⟶ Function
The
map()
the method creates a new array populated with the results of calling a provided function on every element in the calling array.const array1 = [1, 4, 9, 16]; // Pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // Expected output: Array [2, 8, 18, 32]
Challenges
/*
Challenge 1:
Given an array of numbers, return an array of each number, squared
*/
const nums = [1, 2, 3, 4, 5]
// --> [1, 4, 9, 16, 25]
// Your code here
const arr1 = nums.map((x) => x * x)
console.log(arr1)
/*
Challenge 2:
Given an array of strings, return an array where
the first letter of each string is capitalized
*/
const names = ["alice", "bob", "charlie", "danielle"]
// --> ["Alice", "Bob", "Charlie", "Danielle"]
// Your code here
const arr2 = names.map((x) =>
x = x.charAt(0).toUpperCase() + x.substring(1)
)
console.log(arr2)
/*
Challenge 3:
Given an array of strings, return an array of strings that wraps each
of the original strings in an HTML-like <p></p> tag.
E.g. given: ["Bulbasaur", "Charmander", "Squirtle"]
return: ["<p>Bulbasaur</p>", "<p>Charmander</p>", "<p>Squirtle</p>"]
*/
const pokemon = ["Bulbasaur", "Charmander", "Squirtle"]
const arr3 = pokemon.map((x) => `<p> ${x} </p>`)
console.log(arr3)
// const paragraphs = pokemon.map(mon => {
// return `<p>${mon}</p>`
// })
String Interpolation
String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the series a template literal is used. Using string interpolation in JavaScript, values like variables, mathematical expressions, and calculations can also be added.
const name="Abdul Rawoof"
const company = "Tutorials Point"
let salary = 18000
let increment = 2000
let mail = 'abdul@gmail.com'
console.log(`Employee name is ${name} and the company is ${company}Salary of ${name} after increment is ${increment}:${salary+increment}Contact details of ${name} is ${mail}`)
Quiz on .map()
What does the
.map()
array method do?Returns a new array. Whatever gets returned from the callback
function provided is placed at the same index in the new array.
Usually, we take the items from the original array and modify them
in some way.
What do we usually use
.map()
for in React?Convert an array of raw data into an array of JSX elements
that can be displayed on the page.
Why is using
.map()
better than just creating the componentsmanually by typing them out?
It makes our code more "self-sustaining" - not requiring
additional changes whenever the data changes.
Project
Airbnb review App
Snap Shots:
Responsive Website
Reviews
Solo Project 2
Travel Journal using props and data.js
add event listeners
mouse events⟶
We can add event listeners in JS just like properties are added in HTML
for Ex⟶
export default function App() {
function handleClick() {
console.log("I was clicked!")
}
function handleOnMouseOver() {
console.log("MouseOver")
}
/**
* Challenge:
* Log something to the console when the mouse hovers over the image
*/
return (
<div className="container">
<img
src="https://picsum.photos/640/360"
onMouseOver={handleOnMouseOver}
/>
<button onClick={handleClick}>Click me</button>
</div>
)
}
Here in the IMG tag we added a Mouse Listener onMouseOver which tells us about the mouse hovers on the img and onClick listener on the button will tell us about the button has been clicked
The EventListeners request a function using which we can add functionalities to that particular element
In Vanilla JS we do ⟶
document.getElementById("myBtn").addEventListener("click", displayDate);
Props vs State Quiz
How would you describe the concept of "state"?
A way for React to remember saved values from within a component.
This is similar to declaring variables from within a component,
with a few added bonuses (which we'll get to later)
When would you want to use props instead of state?
Anytime you want to pass data into a component so that
the component can determine what will get displayed on the
screen.
When would you want to use state instead of props?
Anytime you want a component to maintain some values from
within the component. (And "remember" those values even
when React re-renders the component).
What does "immutable" mean? Are props immutable? Is the state immutable?
Unchanging. Props are immutable. The state is mutable.
React.useState() Method
useState
is a React Hook that lets you add a state variable to your component.
const [state, setState] = useState(initialState)
initialState
: The value you want the state to be initially. It can be a value of any type, but there is a special behaviour for functions. This argument is ignored after the initial render.
Returns
useState
returns an array with exactly two values:
The current state. During the first render, it will match the
initialState
you have passed.The
set
a function that lets you update the state to a different value and trigger a re-render.
The convention is to name state variables like [something, setSomething]
using array destructuring.
export default function App() {
const [isImportant, setIsImportant] = React.useState("Yes")
/**
* Challenge:
* 1. Create a function called `handleClick` that runs
* setIsImportant("No")
* 2. add a click event listener to the div.state--value
* that runs `handleClick` when the div is clicked.
*/
function handleClick() {
if(isImportant == "Yes") {
setIsImportant("No")
}else {
setIsImportant("Yes")
}
//isImportant == "Yes" ? setIsImportant("No") : setIsImportant("Yes")
}
return (
<div className="state">
<h1 className="state--title">Is state important to know?</h1>
<div className="state--value" onClick = {handleClick}>
<h1>{isImportant}</h1>
</div>
</div>
)
}
state array destructuring
import React from "react"
export default function App() {
//Destructuring
const [isImportant, func] = React.useState("Yes")
console.log(isImportant) //Yes
return (
<div className="state">
<h1 className="state--title">Is state important to know?</h1>
<div className="state--value">
<h1>{isImportant}</h1>
</div>
</div>
)
}
const [count, setCount] = React.useState(0)
/**
* Note: if you ever need the old value of state
* to help you determine the new value of state,
* you should pass a callback function to your
* state setter function instead of using
* state directly. This callback function will
* receive the old value of state as its parameter,
* which you can then use to determine your new
* value of state.
*/
//Do this
function add() {
setCount(prevCount => prevCount + 1)
}
//Dont do this
function subtract() {
setCount(count - 1)
}