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
Here are some changes you can try on your code:
Home.js
User.js
Your code works as expected at my end. What I did is just wrapping the Routes inside a Router element.
App.jsx