React review bagian 3
Andi Ismail
Posted on November 17, 2022
Review materi ract js
pnpm create vite
React > Javascript
pnpm install
pnpm install react-router-dom
Implementasikan routing pada react dengan menggunakan react-router-dom ?
//main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { BrowserRouter } from "react-router-dom";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
//App.jsx
import './App.css'
import {Routes, Route} from "react-router-dom"
function App() {
return (
<Routes>
<Route path='/' element={<h1>Hello</h1>} />
<Route path='/dashboard' element={<h1>Hello</h1>} />
</Routes>
)
}
export default App
Tangkaplah sebuah pparams dari sebuah routes dan render ke komputer jsx? misal blog/1 nanti ditangkap blog 1 ?
Jawabannya, kita buat Blog.jsx
//Blog.jsx
import React from 'react'
import { useParams } from 'react-router-dom'
export default function Blog() {
const {id} = useParams()
return (
<div>
<h1>Blog {id}</h1>
</div>
)
}
kita daftarkanke APp.jsx
//App.jsx
import './App.css'
import {Routes, Route} from "react-router-dom"
import Blog from './pages/Blog'
function App() {
return (
<Routes>
<Route path='/' element={<h1>Hello</h1>} />
<Route path='/dashboard' element={<h1>Dashboard</h1>} />
<Route path='/blog/:id' element={<Blog />} />
</Routes>
)
}
export default App
Buatlah sebuah screen yang mengimplementasikan outlet pada react router dom?
Jawabannya, kita import Outlet dari react router dom
//App.jsx
import Outlet from "react-router-dom"
const Dashboard =()=>{
return (
<div className='App'>
<h1>Dashboard</h1>
<Outlet />
</div>
)
}
<Route path='/dashboard' element={<Dashboard />} >
<Route index element={<h3>Main Dashboard</h3>} />
<Route path='user' element={<h3>User</h3>} />
<Route path='message' element={<h3>Message</h3>} />
</Route>
//App.jsx
import './App.css'
import {Routes, Route, Outlet} from "react-router-dom"
import Blog from './pages/Blog'
const Dashboard =()=>{
return (
<div className='App'>
<h1>Dashboard</h1>
<Outlet />
</div>
)
}
function App() {
return (
<Routes>
<Route path='/' element={<h1>Hello</h1>} />
<Route path='/dashboard' element={<Dashboard />} >
<Route index element={<h3>Main Dashboard</h3>} />
<Route path='user' element={<h3>User</h3>} />
<Route path='message' element={<h3>Message</h3>} />
</Route>
<Route path='/blog/:id' element={<Blog />} />
</Routes>
)
}
export default App
Implementasikan sebuah protected route login dan logout?
Jawaban
kita set user belum login (false)
//App.jsx
function App() {
const [isLogin, setIsLogin]= useState(false) //ganti disini login /logout
if (isLogin){
return (
<Routes>
<Route path='/' element= {<h1>Dashboard</h1>} />
<Route path='/users' element= {<h1>Users</h1>} />
</Routes>
)
}
return (
<Routes>
<Route path='/' element= {<h1>Login Page</h1>} />
<Route path='/about' element= {<h1>About Page</h1>} />
<Route path='*' element= {<h1>Page not found</h1>} />
</Routes>
)
}
berarti dia hanya bisa mengakses login page dan about page
mau coba akses users, tidak bisa karena belum login.
sekarang kita set user sudah login (true)
const [isLogin, setIsLogin]= useState(true)
kita sudah tidak berada di halaman login page lagi, melainkan sudah berada di dashboard.
implementasikan global state dengan react context, misalanya buat sebuah data user yang bisa dipanggil dari semua komponent?
Jawabannya
kita buat file Usercontextprovider.jsx
//userContextProvider.jsx
import { useState } from "react";
import { createContext } from "react";
export const UserContext = createContext();
export default function UserContextProvider({ children }) {
const [data, setData] = useState({
username: "andi",
email: "andi@andi.com",
avatar: "https://picsum.photos/seed/halo/200/200",
});
return <UserContext.Provider value={{ data, setData }}>{children}</UserContext.Provider>;
}
//App.jsx
function App() {
const [isLogin, setIsLogin]= useState(true) //ganti disini login /logout
if (isLogin){
return (
<Routes>
<Route path='/' element= {<h1>Dashboard</h1>} />
<Route path='/users' element= {<User />} />
</Routes>
)
}
return (
<Routes>
<Route path='/' element= {<h1>Login Page</h1>} />
<Route path='/about' element= {<h1>About Page</h1>} />
<Route path='*' element= {<h1>Page not found</h1>} />
</Routes>
)
}
kita buat User.jsx dan dafatarkan ke App.jsx
import React, { useContext } from "react";
import { UserContext } from "../context/UserContextProvider";
export default function User() {
const { data } = useContext(UserContext);
return (
<div>
<h1>Welcome, {data.username}</h1>
</div>
);
}
di main.jsx
//main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { BrowserRouter } from "react-router-dom";
import UserContextProvider from "./context/UserContextProvider";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<BrowserRouter>
<UserContextProvider>
<App />
</UserContextProvider>
</BrowserRouter>
</React.StrictMode>
);
kita masuk ke page users
Implementasikan global state dengan react context yang datanya berasal dari sebuah api https://jsonplaceholder.typicode.com/posts. untuk soal diatas statis sekarang kita mabil data dari api.
Jawabannya
kita buat file BlogContextProvider.jsx hampir sama dengan menampilkan data static di atas
//BlogContextProvider
import { createContext, useState, useEffect } from "react";
export const BlogContext = createContext();
export default function BlogContextProvider({ children }) {
const [post, setPost] = useState([]);
const getBlogPost = async () => {
const data = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "GET",
header: {
"Content-Type": "application/json",
},
});
const result = await data.json();
return result;
};
useEffect(() => {
getBlogPost()
.then((res) => {
setPost(res);
})
.catch((err) => {
console.error(err);
});
}, []);
return (
<BlogContext.Provider value={{ post, setPost }}>
{children}
</BlogContext.Provider>
)
}
//Blogs.jsx
import React from 'react'
import { useContext } from 'react'
import { BlogContext } from '../context/BlogContextProvider'
export default function Blogs() {
const {post} = useContext(BlogContext)
return (
<div>
<h1>Blog</h1>
{post.map((e)=>(
<div key={e.id}>
<h2>{e.title}</h2>
<h4>{e.body}</h4>
</div>
))}
</div>
)
}
//App.jsx
function App() {
const [isLogin, setIsLogin]= useState(true) //ganti disini login /logout
if (isLogin){
return (
<Routes>
<Route path='/' element= {<h1>Dashboard</h1>} />
<Route path='/users' element= {<User />} />
<Route path='/blog' element= {<Blogs />} />
</Routes>
)
}
//main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { BrowserRouter } from "react-router-dom";
import UserContextProvider from "./context/UserContextProvider";
import BlogContextProvider from "./context/BlogContextProvider";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<BrowserRouter>
<UserContextProvider>
<BlogContextProvider>
<App />
</BlogContextProvider>
</UserContextProvider>
</BrowserRouter>
</React.StrictMode>
);
Implementasikan custom hook untuk blog context?
Jawabnnya, kita buat useBlog.js
//useBlogs.js
import { useContext } from "react";
import { BlogContext } from "../context/BlogContextProvider";
export default function useBlogs(){
return useContext(BlogContext)
}
//Blogs.jsx
import React from 'react'
import useBlogs from '../hook/useBlog'
//import { useContext } from 'react'
//import { BlogContext } from '../context/BlogContextProvider'
export default function Blogs() {
//const {post} = useContext(BlogContext)
const {post} = useBlogs()
return (
<div>
<h1>Blog</h1>
{post.map((e)=>(
<div key={e.id}>
<h2>{e.title}</h2>
<h4>{e.body}</h4>
</div>
))}
</div>
)
}
Terimakasih.
https://github.com/andiks2018/JvalleyReact-reviewBag3.git
Posted on November 17, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024