React review bagian 3
Published: 2022-11-17 06:24:22

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

```

![Image Hello](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dai7qurfhgcxwp0uqj9.png)

---

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

```

![Image hal3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vttf15cky7xq731wtqgn.png)

---

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>

```

![Image main](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5v4jccwo3ybog0l85isq.png)

![Image user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4oer9zy50zkbdns266h5.png)

![Image message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/piyufh4g2zsw91svg5hc.png)

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

![Image login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksn4l8cazojg9os3w2hz.png)

![Image about](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8bkkkc19bjjdp71sigk.png)

mau coba akses users, tidak bisa karena belum login.

![Image users](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/slz61l9ec7jekzfwrggp.png)

sekarang kita set user sudah login (true)

`const [isLogin, setIsLogin]= useState(true)`

![Image akses users](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2w9qyrpaylb7vif0x22r.png)

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

![Image dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpouh0ylkgggv43dabhn.png)

---

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

```

![Image dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0cyxfc2c91xvwju5bita.png)

kita masuk ke page users

![Image user andi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0j5lh8i3o9b8taaadza.png)

---

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

![Image blog API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trtzbjk7wdde2lwsixaz.png)

---

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

```

![Image custom hook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/so41bf0qakhuqxmh4rol.png)

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