skip to Main Content

I’m trying to figure out how I can render a new card on a new route using the id. I’ve tried moving the useParams to the card component. I’m struggling to understand how to get the id to use the

App.js

import { useState, useEffect } from 'react'
import { Route, Routes } from 'react-router-dom'
import Home from './pages/Home.jsx'
import User from './pages/User.jsx'
import './App.css'

function App() {
  const [users, setUsers] = useState([])
  useEffect(() =>{
      fetch('https://jsonplaceholder.typicode.com/users')
      .then(res => res.json())
      .then(data => setUsers(data))
  }, [])

  return (
    <> 
    <Routes>
     <Route path="/" element={<Home users={users}/>}/>
     <Route path='/user/:id' element={<User users={users}/>}/> 
    </Routes>
   </>
  )
}

export default App

Home.js

import Card from "../components/Card" 


export default function Home({users}){
    return(
        <>
            <div className='card-container'>
                {users && <Card users={users}/>}
            </div>
        </>
    )
}

Card.js

export default function Card( {users}){
    return(
     <>
        {users.map((user) => {
            return(
                <div className='card' key={user.id}>
                    <h2>{user.name}</h2>
                    <p><strong>City:</strong> {user.address.city}</p>
                </div>
            )
        })}
     </>
    )
} 

User.js

import { useParams } from "react-router-dom"

export default function User({users}){
    const {id} = useParams()
    const intId = parseInt(id)

    const filteredUsers = users.filter(user => { 
        return intId === user.id
    })

    if(filteredUsers.length > 0){
    return(
        <div className="card-container">
            <div className='card' key={filteredUsers[0].id} >
                <h2>{filteredUsers[0].name}</h2>
                <p><strong>City:</strong> {filteredUsers[0].address.city}</p>
                <p>Email:{filteredUsers[0].email}</p>
                <p>Website:{filteredUsers[0].website}</p>
                <p>Company:{filteredUsers[0].company.name}</p>
            </div>    
        </div>
       )
    }
}

I’ve tried moving useParams to the card component and I just cannot figure it out

2

Answers


  1. Here are some changes you can try on your code:

    Home.js

    import { Link } from 'react-router-dom'
    
    export default function Home({ users }) {
      return (
        <div className='card-container'>
          {users && users.map((user) => (
            <div className='card' key={user.id}>
              <h2>{user.name}</h2>
              <p><strong>City:</strong> {user.address.city}</p>
              <Link to={`/user/${user.id}`}>View Details</Link>
            </div>
          ))}
        </div>
      )
    }
    

    User.js

    import { useParams } from "react-router-dom"
    
    export default function User({ users }) {
      const { id } = useParams()
      const intId = parseInt(id)
    
      const filteredUsers = users.filter(user => user.id === intId)
    
      if (filteredUsers.length > 0) {
        const user = filteredUsers[0]
        return (
          <div className="card-container">
            <div className='card' key={user.id} >
              <h2>{user.name}</h2>
              <p><strong>City:</strong> {user.address.city}</p>
              <p>Email: {user.email}</p>
              <p>Website: {user.website}</p>
              <p>Company: {user.company.name}</p>
            </div>
          </div>
        )
      }
      return null; // Or you can display a message for user not found
    }
    
    Login or Signup to reply.
  2. Your code works as expected at my end. What I did is just wrapping the Routes inside a Router element.

    App.jsx

    import { useState, useEffect } from "react";
    import { Route, Routes, BrowserRouter as Router } from "react-router-dom";
    import Home from "./pages/Home.jsx";
    import User from "./pages/User.jsx";
    import "./App.css";
    
    function App() {
      const [users, setUsers] = useState([]);
      useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then((res) => res.json())
          .then((data) => setUsers(data));
      }, []);
    
      return (
        <Router>
          <Routes>
            <Route path="/" element={<Home users={users} />} />
            <Route path="/user/:id" element={<User users={users} />} />
          </Routes>
        </Router>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search