passing a dynamic url with React

Viewed 3525

Thanks to everyone for your efforts to help me before at How to pass and retrieve data over the url in React I don't know why it wasn't working but I decided to simplify things and just pass a string instead of an object but it still isn't being read. Instead of having a dynamic url, it just passes the string ":i" or ":book.id" or whatever value I try to use in the Link tag.

App.js

import { BrowserRouter as Router, Link, Route, Switch } from "react-router-dom";
<Router>
      <div className="App">
        <Header />

        <Switch>
          <Route path="/" component={Main} />
          <Route path='/:i' component={Single} />
        </Switch>
      </div>
    </Router>


Main.js

import React, { useState } from "react";
import data from "../data/books.json";
import "./main.css";
import { BrowserRouter as Router, Link } from "react-router-dom";
import Search from "./Search";


function importAll(r) {
  let images = {};
  r.keys().forEach((item, index) => {
    images[item.replace("./", "")] = r(item);
  });
  console.log(images);
  return images;
}

const Main = () => {
  
  const images = importAll(require.context("../images", false, /\.(jpe?g)$/));
  console.log(images);
 

  return (
  
    <div id="main">
     
      {data.map((book, i) => {
        return (
          <div key={i} className="squares">
            <img
              src={images[book.picture]}
              className="covers"
              alt="book cover"
            />
            <h3>
//////////////////////!!!!!!!!!!!!!!!!!!! here
              <Link to="/:i">{book.title}</Link> 
//////////////////////!!!!!!!!!!!!!!!!!!!
            </h3>
            <p>
              Author: <em>{book.author}</em>
            </p>
            <p>
              Price: <strong>{book.price}$</strong>
            </p>
            <p>{book.inventory} left in stock</p>
          </div>
        );
      })}
      ;
    </div>
  );
};

export default Main;

Single.js


import React, { useState } from "react";
import data from "../data/books.json";
import {
  BrowserRouter as Router,
  Link,
  Route,
  useParams,
} from "react-router-dom";

const Single = (props) => {

  let id = useParams();
  console.log("1", id); ////logs ':i' or whatever other value I am trying to search by


1 Answers

You should not pass params in Link like this.

You pass parameter value, like id.

<Link to={`/${i}`}>

And then in route you receive it

<Switch>
  <Route path="/:id" children={<Child />} />
</Switch>

Here is doc with examples

Related