You are on page 1of 11

Nested Components Javascript in JSX

// Arrow function shorthand component ● Enclose between {}


const Person = () => <h1>Mike Taylor</h1>
● Must be an expression (return a value)
function App(){
// Arrow function component
const name = 'Mike'
const Message = () => {
return (
return <h1>Hello</h1>
<>
}
<h1>Hello {name}</h1>
<p>{name === 'Mike' ? '(admin)': '(user)'}</p>
// Function component
</>
function HelloWorld(){
)
return (
}
<>
======================
<Message />
<Person />
</>)}

Inline CSS Component Properties (Props)


function App(){ function App()
return <h1 style={{ color: 'red' }}>Hello return <Person name='Mike' age={29} />
}
}
(src/App.css) const Person = (props) => {
h1 { return <h1>Name: {props.name}, Age:
color: red;} h1>
}

// or props object deconstructing


const Person = ({name, age}) => {
return <h1>Name: {name} Age: {age}</h1>
}

List List with key (for React internal reference)


const people = [ function App(){

{id: 1, name: 'Mike', age: 29}, return (


{id: 2, name: 'Peter', age: 24}, people.map(person => {

{id: 3, name: 'John', age: 39}, return <Person key={person.id}


name={person.name} age={person.age}/>
]
}))}
function App(){ =========================================

return ( Click Event


const clickHandler = () => alert('Hello World')
people.map(person => { function App(){
return (
return <Person name={person.name} <>
age={person.age}/>}))} <h1>Welcome to my app</h1>
<button onClick={clickHandler}>Say Hi</button>
const Person = (props) => { </>
)
return ( }
====================================
<h1>Name: {props.name}, Age: To pass arguments we need to use arrow
{props.age}</h1>)} function
const clickHandler = (message) => alert(message)
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={() => clickHandler('Hello
World')}>Say Hi</button>
</> )

useState with object setState functional form


const DisplayTitle = () => { function Counter() {

const [person, setPerson] = useState({name: const [count, setCount] = useState(0)


'Mike', age: 29})
// Use a function to set State
const handleClick = () => setPerson({...person,
age: 35}) const increase = () => setCount(() => count + 1)
return <> return (

<h2>{title}</h2> <>

<button type="button" className="btn" <h1>Counter</h1>


onClick={handleClick}>
<p>{count}</p>
Change Age
<button onClick={increase} className='btn'> +
</button> </button>

</> <button onClick={() => setCount(() => count - 1)}


}; className='btn'> - </button>

</>)}

USEEFFECT Conditional useEffect


By default useEffect function is Conditional need to be place inside useEffect
execute after every re-render. You function
can then execute code everytime
useEffect(() => {
component update.
import React, { useEffect } from 'react';
if (value > 0) {
function IncreaseValue() {
document.title = `New value: ${value}`
const [value, setValue] = useState(0)
useEffect(() => {
}})
document.title = `New value: ${value}`
})
return <button onClick={() =>
setValue(value + 1)}>Increase</button>
}

nline Logical && Operator.


Conditional Rendering Display only if first expression is truthy
truthy = Not : 0, "", null, undefined, and
function DisplayGreeting() {
NaN
const [name, setName] = useState('Mike')
function DisplayUserInfo({active}) {
if (name === 'Mike') {
return <h1>Hello admin {name}</h1> return (

} <div>

return <h1>Hello user {name}</h1> { active && <h1>User is active</h1>}

} </div>

);
Inline If-Else
}
return (

<div> Multiple inline If


<span className={count === 0 && 'text-gray-500' ||
The user is <b>{isLoggedIn ? 'currently' : count > 0 && 'text-green-500' || count < 0 &&
'not'}</b> logged in. 'text-red-500'}>{count}</span>

</div> ======================
);
}

AXIOS

How to Make a GET Request How to Make a POST Request


To fetch data or retrieve it, make a To create new data, make a POST
GET request. request.

First, you're going to make a request According to the API, this needs to be
for individual posts. If you look at the performed on the /posts endpoint. If you
endpoint, you are getting the first look at the code below, you'll see that
post from the /posts endpoint: there's a button to create a post:

import axios from "axios"; import axios from "axios";


import React from "react"; import React from "react";
const baseURL = const baseURL = "https://jsonplaceholder.typicode.com/posts";
"https://jsonplaceholder.typicode.com/posts/1";
export default function App() {
export default function App() { const [post, setPost] = React.useState(null);
const [post, setPost] = React.useState(null);
React.useEffect(() => {
React.useEffect(() => { axios.get(`${baseURL}/1`).then((response) => {
axios.get(baseURL).then((response) => { setPost(response.data);
setPost(response.data); });
}); }, []);
}, []);
function createPost() {
if (!post) return null; axios
.post(baseURL, {
return ( title: "Hello World!",
<div> body: "This is a new post."
<h1>{post.title}</h1> })
<p>{post.body}</p> .then((response) => {
</div> setPost(response.data);
); });
}
}
if (!post) return "No post!"

return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={createPost}>Create Post</button>
</div>
);}

How to Make a PUT Request How to Make a DELETE Request


To update a given resource, make a Finally, to delete a resource, use the
PUT request. DELETE method.

In this case, you'll update the first As an example, we'll delete the first
post. post.

To do so, you'll once again create a Note that you do not need a second
button. But this time, the button will argument whatsoever to perform this
call a function to update a post: request:

import axios from "axios"; import axios from "axios";


import React from "react"; import React from "react";

const baseURL = const baseURL = "https://jsonplaceholder.typicode.com/posts";


"https://jsonplaceholder.typicode.com/posts";
export default function App() {
export default function App() { const [post, setPost] = React.useState(null);
const [post, setPost] = React.useState(null);
React.useEffect(() => {
React.useEffect(() => { axios.get(`${baseURL}/1`).then((response) => {
axios.get(`${baseURL}/1`).then((response) => { setPost(response.data);
setPost(response.data); });
}); }, []);
}, []);
function deletePost() {
function updatePost() { axios
axios .delete(`${baseURL}/1`)
.put(`${baseURL}/1`, { .then(() => {
title: "Hello World!", alert("Post deleted!");
body: "This is an updated post." setPost(null)
}) });
.then((response) => { }
setPost(response.data);
}); if (!post) return "No post!"
}
return (
if (!post) return "No post!" <div>
<h1>{post.title}</h1>
return ( <p>{post.body}</p>
<div> <button onClick={deletePost}>Delete Post</button>
<h1>{post.title}</h1> </div>
<p>{post.body}</p> );
<button onClick={updatePost}>Update
Post</button> }
</div>
);

}
In most cases, you do not need the data
that's returned from the .delete() method.
In the code above, you use the PUT
method from Axios. And like with the
POST method, you include the
properties that you want to be in the
updated resource.

Again, using the .then() callback, you


update the JSX with the data that is
returned.

How to Handle Errors with Axios =============================


What about handling errors with =============================
Axios? ASYNC/AWAIT NODE JS
async function hello() { return "Hello"
What if there's an error while };
making a request? For example, hello();
you might pass along the wrong
data, make a request to the wrong Copy to Clipboard
endpoint, or have a network error. Ah. Invoking the function now returns a promise. This is
one of the traits of async functions — their return
values are guaranteed to be converted to promises.
To simulate an error, you'll send a
You can also create an async function expression, like
request to an API endpoint that so:
doesn't exist: /posts/asdf.
let hello = async function() { return
"Hello" };
hello();
This request will return a 404
status code:
Copy to Clipboard
And you can use arrow functions:
import axios from "axios";
let hello = async () => "Hello";
import React from "react";
const baseURL =
"https://jsonplaceholder.typicode.com/posts";
Copy to Clipboard
export default function App() { These all do basically the same thing.

const [ post, setPost] = React.useState(null); To actually consume the value returned when the
promise fulfills, since it is returning a promise, we could
use a .then() block:
error, setError] =
const [

React.useState(null); hello().then((value) =>


console.log(value))

React.useEffect(() => { Copy to Clipboard


or even just shorthand such as
// invalid url will trigger an 404 error
hello().then(console.log)
axios.get(`${baseURL}/asdf`).then((response) => {
setPost(response.data); Copy to Clipboard
Like we saw in the last article.
}).catch(error => {
So the async keyword is added to functions to tell
setError( error); them to return a promise rather than directly returning
the value.
});
==============================
}, []); await can be put in front of any async promise-based
function to pause your code on that line until the
promise fulfills, then return the resulting value.

if (error) return `Error: ${error.message}`; You can use await when calling any function that
returns a Promise, including web API functions.
if (! post) return "No post!"
Here is a trivial example:

async function hello() {


return await Promise.resolve("Hello");
return (
};

< div>
hello().then(alert);
h1>{post.title}</h1>
<

p post.body}</p>
< >{

</ div>

);

async function myFetch() {


let response = await fetch('coffee.jpg');

if (!response.ok) {
throw new Error(`HTTP error! status:
${response.status}`);
}

let myBlob = await response.blob();

let objectURL = URL.createObjectURL(myBlob);


let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}

myFetch()
.catch(e => {
console.log('There has been a problem with your fetch
operation: ' + e.message);
})

=============================
Adding error handling

And if you want to add error handling, you've got a


couple of options.

You can use a synchronous try...catch structure with


async/await. This example expands on the first
version of the code we showed above:

async function myFetch() {

try {

let response = await fetch('coffee.jpg');

if (!response.ok) {

throw new Error(`HTTP error! status: ${response.status}`);

let myBlob = await response.blob();

let objectURL = URL.createObjectURL(myBlob);

let image = document.createElement('img');

image.src = objectURL;

document.body.appendChild(image);

} catch(e) { console.log(e);}}myFetch();

You might also like