React review bagian 3

andiismail

Andi Ismail

Posted on November 17, 2022

React review bagian 3

Review materi ract js

pnpm create vite
React > Javascript
pnpm install
pnpm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

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>
);

Enter fullscreen mode Exit fullscreen mode
//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

Enter fullscreen mode Exit fullscreen mode

Image Hello


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>
  )
}

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Image hal3


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>

Enter fullscreen mode Exit fullscreen mode

Image main

Image user

Image message

//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

Enter fullscreen mode Exit fullscreen mode

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>
  )
}

Enter fullscreen mode Exit fullscreen mode

berarti dia hanya bisa mengakses login page dan about page

Image login

Image about

mau coba akses users, tidak bisa karena belum login.

Image users

sekarang kita set user sudah login (true)

const [isLogin, setIsLogin]= useState(true)

Image akses users

kita sudah tidak berada di halaman login page lagi, melainkan sudah berada di dashboard.

Image 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>;
}

Enter fullscreen mode Exit fullscreen mode
//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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}

Enter fullscreen mode Exit fullscreen mode

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>
);

Enter fullscreen mode Exit fullscreen mode

Image dashboard

kita masuk ke page users

Image user andi


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>
  )
}

Enter fullscreen mode Exit fullscreen mode
//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>
  )
}

Enter fullscreen mode Exit fullscreen mode
//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>
    )
  }
Enter fullscreen mode Exit fullscreen mode
//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>
);
Enter fullscreen mode Exit fullscreen mode

Image blog API


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)
}
Enter fullscreen mode Exit fullscreen mode
//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>
  )
}

Enter fullscreen mode Exit fullscreen mode

Image custom hook


Terimakasih.
https://github.com/andiks2018/JvalleyReact-reviewBag3.git

💖 💪 🙅 🚩
andiismail
Andi Ismail

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