Router Simple example React Js ?

This is the simple example os React Router using fetch API , so here we will be creating custom route for each link fetched from the API.

Output of this will be.

About page with fetch call to the list of items

screenshot_01.png

screenshot_02.png

APP.js


import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import About from './Components/About/About'
import AboutSingle from './Components/About/AboutSingle/AboutSingle'
import Home from './Components/Home/Home'
import Main from './Components/Main/Main'
import Nav from './Components/Nav/Nav'

const App = () => {
  return (
    <Router>
      <div>
        <Nav />
        <Switch>
          <Route path='/' exact component={Main} />
          <Route path='/home' component={Home} />
          <Route path='/about' exact component={About} />
          <Route path='/about/:id' component={AboutSingle} />
        </Switch>
      </div>
    </Router>
  )
}

export default App

About

import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'

const About = () => {
  const [items, setItems] = useState([])

  const fetchItems = async () => {
    const itemData = await fetch('https://fakestoreapi.com/products')
    const itemsReceived = await itemData.json()
    // console.log(itemsReceived)

    setItems(itemsReceived)
  }

  useEffect(() => {
    fetchItems()
  }, [])

  return (
    <div>
      <h2>about</h2>
      {items.map((item) => (
        <h1 key={item.id}>
          <Link to={`/about/${item.id}`}>{item.title}</Link>
        </h1>
      ))}
    </div>
  )
}

export default About

About Single



import React, { useState, useEffect } from 'react'
import './AboutSingle.css'

const AboutSingle = ({ match }) => {
  const [singleAbout, setsingleAbout] = useState([])

  const fetchSingleAbout = async () => {
    const singleFetchObject = await fetch(
      `https://fakestoreapi.com/products/${match.params.id}`
    )
    const singleObject = await singleFetchObject.json()

    setsingleAbout(singleObject)
  }

  useEffect(() => {
    fetchSingleAbout()
  }, [])

  return (
    <div className='single-about'>
      <img src={singleAbout.image} alt='' srcset='' />
    </div>
  )
}

export default AboutSingle
© 2021 GitHub, Inc.