0

sorry I'm new to JS and especially React. Can someone help me please. I am creating my first react app while still learning it and have issues with react router dynamic urls and data inside.

Instead of backend I am currently storing list of items (tools) inside a context provider component as an array of objects. It wraps my entire app and I can access my tools anywhere. But now I need to make tools clickable in the list, and I am having trouble with it.

in my toolslist.jsx I have links

<Link to={`/tools/${item.id}`}>

<p>{item.name}</p>

</Link>    

in toolsdetails -

import { React, useContext } from "react";
import { useParams } from "react-router-dom";
import ToolsContext from "../../context/toolsListContext";

function ToolsDetails() {
  const params = useParams();
  const id = params.id;
  const { tools } = useContext(ToolsContext);
  const tool = tools.find(item => item.id === id);
  console.log(id, tools, tool); // getting tool undefined error..
  return <div>{tools[id].name}</div>; //I don't need an entire tools object here...
}

export default ToolsDetails;

and in the app routes are:

function App() {
  return (
    <Routes>
      <Route exact path="/" element={<Main />}/>
      <Route path="/library" element={<Library />} />
      <Route path="/tools/:id" element={<ToolsDetails />} />
    </Routes>
  );
}

I know how to get the data using the context, but in toolsdetails I don't really need it, AFAIK router should be able to pass the required object with the link prop. However I'm struggling with it, I think it should be used with loader according to the docs but their examples are with external apis. My data is right there in context.

rivage
  • 1
  • What do you need to pass on to `ToolsDetails`? You can use the `state` prop of `Link` component to pass the data that you need. You can access this data in `ToolsDetails` with the `useLocation` hook. – ivanatias Jan 29 '23 at 20:54
  • In toolsdetails I need the object with the ID on the link to render all the information about the item (name, picture). useLocation gives me an object with the url, as I understand I can use it to filter/find the needed object by ID from the array of all objects. But it seems overkill to load the entire array in toolsdetails component? – rivage Jan 30 '23 at 04:21

0 Answers0