I am new to this concept i am trying to map the items and in that i want make each and every item should navigate to another page. But I am getting an error while doing that .. Please help me with this !
i want to know how to navigate the each item to another page when you click on it and it should be a different page for every items in the list .
import React, { useEffect, useState } from "react";
import ItemsData from "../components/Item";
import { useDispatch, useSelector } from "react-redux";
import { getAllItems } from "../actions/itemActions";
import "./Homepage.css";
export default function Homepage() {
const dispatch = useDispatch(); // by this var we can dispatch the action.
const itemsstate = useSelector((state) => state.getAllItemsReducer);
// destructured the var
const { items, error, loading } = itemsstate; // with this help of var we can track whether it is loading or error whether we got the response about items.
useEffect(() => {
dispatch(getAllItems());
}, []);
return (
// we are using the conditional rendering.
<div>
<div className="row">
<div className="col-12 px-0 d-flex flex-lg-row flex-md-row flex-column justify-content-between flex-wrap">
{loading ? (
<h1>Loading...</h1>
) : error ? (
<h1>Something went Wrong </h1>
) : (
items.map((items) => {
// data comes from backend.
return (
<div className="col-md-4" key={items._id}>
<div>
<ItemsData items={items} />
</div>
</div>
);
})
)}
</div>
</div>
</div>
);
}
CodePudding user response:
Create a route with params like in the exemple there:
and useNavigate or <Navigate>
component with your url params:
CodePudding user response:
map() function iterates through your array and returns a new array.
The callback you use can access up to 3 parameters, the 1st one being the element being iterated.
In your case you're naming your element also items
, this can be confusing to Javascript not knowing which items.id
to pass to the key and items
to pass to ItemsData
Changing the element to item
should solve your problem
Also consider changing the name of the prop in your ItemsData, because that component should receive 1 item at a time, not multiple
items.map((item) => {
// data comes from backend.
return (
<div className="col-md-4" key={item._id}>
<div>
<ItemsData items={item} /> //probably consider changing this prop name
</div>
</div>
);
})