I am encountering issues with routing when using the useParams hook

I'm currently working on a project for an online car shop. My goal is to have the ProductDetails displayed on a new page when the user clicks on "more details" in the Products section, but unfortunately, it's not working as expected. Firstly, it's not displaying the correct path in the browser bar, which should be

"http://localhost:3000/product-details"
, and secondly, it keeps rendering the Home page.

App.js

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { Navigate } from 'react-router-dom';

import Cart from './pages/Cart';
import Home from './pages/Home';
import ProductDetails from './pages/ProductDetails';


function App() { 
 return (
   <Router>
     <Routes>
       <Route>
         <Route path="/home" element={<Home />} />
         <Route path="/cart" element={<Cart />} />
         <Route path="/product-details/:id" element={<ProductDetails />} />
         <Route path="*" element={<Navigate to ="/home" replace />} />
       </Route>
     </Routes>
   </Router>
 );
}

export default App;

Products.js

import React from 'react';
import { Link } from 'react-router-dom';
import toyota from '../assets/images/toyota_camry2023.png'
import honda from '../assets/images/honda_civic2023.png';
import ford from '../assets/images/ford_mustang2023.png';

function Products() {
  const cars = [
    { id: 1, name: 'Toyota Camry', price: 25000, img: toyota },
    { id: 2, name: 'Honda Civic', price: 27000, img: honda },
    { id: 3, name: 'Ford Mustang', price: 35000, img: ford },
  ]

  return (
    <div>
      <h2>Find The Best Deals</h2>
      <h2>Available Cars</h2>
      <ul>
        {cars.map(car => (
          <li key={car.id}>
            <img src={car.img} alt={car.name} />
            <h3>{car.name}</h3>
            <p>Price: ${car.price}</p>
            <Link to={`product-details/${car.id}`} target="_blank">More details</Link>
          </li>
        ))}
      </ul>
    </div>
  )
}

export default Products;

ProductDetails.js

import React from 'react';
import { useParams } from 'react-router-dom';

function ProductDetails() {
  const { id }  = useParams();

  const Product = {
    1: {
      Engine: '2.5L Inline-4 Gas',
      Drivetrain: 'Front-Wheel Drive', 
      Transmission: '8-Speed       Automatic', 
      Warranty: '5 Years / 100000 km'
    },
    2: {
      Engine: 'Turbocharged DOHC 16-valve Inline-4', 
      Drivetrain: 'Front-Wheel-Drive,',    
      Transmission: 'Continuously Variable Automatic', 
      Warranty: '3 Years / 60000 km'
    },
    3: {
      Engine: 'Intercooled Turbo Premium Unleaded I-4', 
      Drivetrain: 'Rear Wheel Drive with limited-slip differential', 
      Transmission: '10-speed automatic transmission', 
      Warranty: '3 years / 60000 km'
    },

  };

 const ProductDetails = Product[id];

 return (
    <div>
      <h2>Car Details</h2>
      <p>{ProductDetails.Engine}</p>
      <p>{ProductDetails.Drivetrain}</p>
      <p>{ProductDetails.Transmission}</p>
      <p>{ProductDetails.Warranty}</p>
      <button>Add to Cart</button>
      <button>Book a Test Drive</button>
    </div>
  )
}

export default ProductDetails;

It seems like there might be an issue with the routing or syntax. Let's work together to resolve this problem. Feel free to provide any other insights that may help me assist you further.

Answer №1

Problem

The component Product is being displayed by the Home component on the route path "/home", and it utilizes relative link target paths. Relative paths are based on the current URL path. For example, when the current URL path is "/home" and a link target is set as to={`product-details/${car.id}`}, the resulting navigation will be to

"/home/product-details/someIdValue"
. If there is no specific route matching this URL path, the wildcard matcher path="*" or "catch all" route will be triggered, redirecting the UI back to "/home".

Solution

To resolve this issue, switch to using absolute link target paths. Absolute paths start from the root directory, indicated by the leading "/" character. Make sure to prepend this character to your link target path values.

For instance, update your code snippet like below:

to={`/product-details/${car.id}`}

Code Example:

const cars = [
  { id: 1, name: 'Toyota Camry', price: 25000, img: toyota },
  { id: 2, name: 'Honda Civic', price: 27000, img: honda },
  { id: 3, name: 'Ford Mustang', price: 35000, img: ford },
]

function Products() {
  return (
    <div>
      <h2>Find The Best Deals</h2>
      <h2>Available Cars</h2>
      <ul>
        {cars.map(car => (
          <li key={car.id}>
            <img src={car.img} alt={car.name} />
            <h3>{car.name}</h3>
            <p>Price: ${car.price}</p>
            <Link to={`/product-details/${car.id}`}>
              More details
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The tooltip chart is not displaying all of its data

I create a dynamic tooltip with a custom chart inside of it. tooltip: { borderRadius: 15, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none', useHTML: true, shared: true, formatter: function() { ...

The x-axis values in Amchart are transitioning rather than shifting

I'm facing an issue with my x-axis values as I'm using real-time amcharts. The x-axis values change every 3 seconds, but instead of smoothly moving, they abruptly change to the next value. I would like it to slide smoothly like this example: htt ...

I encounter internal server errors when trying to upload images in React

Attempting to send a post request with an image, but encountering errors without understanding why.https://i.sstatic.net/W5uk1.png const [image, setImage] = useState([]); const handleImage = (event) => { setImage(...Array(event.target.files ...

Adding values to a knockout data table without refreshing the page

I am currently experiencing difficulties with refreshing my knockout.js DataTable. I have a data table that loads correctly on page load using the attached function method. I also have multiple buttons (Display All, Allowed, Not Allowed) that display the t ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

jQuery plugin that controls scrolling speed using the mousewheel

I am trying to replicate the header design of Google+ which includes a search bar that moves when scrolling. Specifically, when the user scrolls down, the search bar shifts to top:-60px and the second horizontal menu shifts from top:60px to top:0 becoming ...

What is the best way to eliminate the hash from the URL of a single-route Angular application without the need for ui.router?

I came across a question that has been asked before on Stack Overflow, but unfortunately, it remains unanswered and without any comments. In my Angular app, I am working with a single route and I want to find a way to eliminate the # from the URL. If I h ...

Pre-Render Conditions in React - Optimizing Your Components for Faster

Before launching my React application, there are two key conditions that need to be checked: First, it is important to verify if the user is logged in. If not, the user should be redirected to the login page. Secondly, all user settings must be retrieved ...

What is the best approach to combine 'v-for' with 'v-if' in my code?

I have a challenge with two tables - one for books and the other for stock. I am attempting to retrieve books by their name and display them in the stock table. The code snippet I've used below is resulting in an error message being displayed. [v ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...

A guide on validating dates in Angular Ionic5 with the help of TypeScript

I have tried multiple solutions, but none seem to work when validating the current date with the date entered by the user. The date is passed from the user into the function parameters, but how do I perform validation? How can I validate the date? isToday( ...

Express encounters difficulties loading JavaScript files

I'm currently working on building an express web app, but I'm encountering a problem with importing a javascript file. Within board.js, there's a line const utility = require('./utility');. However, this line is causing an error: ...

SQL's ISJSON function is returning false when using JSON.stringify. It seems

I'm on a quest to understand why this specific data is not being recognized as JSON within SQL. It's being sent from the front end using JSON.stringify. '[{\"value\":\"TB12\",\"label\&qu ...

The IMG onclick event for LinkModalDialog does not function properly on Mozilla browsers

I am currently utilizing the following function: function OpenLinkModal(obj){ var arr=showModalDialog("../../files/list_simple.asp","","dialogHeight: 600px; dialogWidth: 450px; edge: Raised; center: Yes; resizable: Yes; status: Yes; scroll: Yes; help ...

Glitch in the scroll glue directive

Currently, I'm attempting to incorporate scroll-glue in order to automatically scroll to the bottom of a message.html page. My approach involved including the directive 'luegg.directives' in the following manner. (function(){ 'use stri ...

What is the best way to send props to a CSS module in React?

Currently utilizing NextJS, I have a route named about that is displayed through page.js. Within /about/page.js, I am incorporating a component called <Hero /> and aiming to pass a prop to <Hero heroHeight={'height: 400px'} /> to my C ...

Move items from one list to another using JavaScript

In my scenario, I have a userlist that is populated from a database. Below is the implementation of the Userlist: <select id="Userlist" name="cars" runat="server" multiple="true" style="width: 270px; height: 200px;"> </select> The objective i ...

Tips for extracting information from a select box that is dynamically populating

I have a dropdown menu displayed in the image below. It contains a "More..." option that, when clicked, loads the next ten data items. Subsequent clicks on "More" will load another set of ten data items each time until the entire list is loaded. How can I ...

Is the VueJs and ChartJs combination causing the chart to be width-responsive, but not height-responsive?

I've exhausted all options, but I can't seem to make the height of my chart respond effectively. The width is behaving as expected, adjusting responsively, but the height stubbornly remains fixed at 400px. Within my primary Vue application, I i ...