Alex Belke
Alex Belke

Reputation: 2233

React Router v4 URL with params error when / at the end

I have a problem with React Router.

I've created a simple App in code sandbox to demonstrate it.

link to the codesandbox

Description

When in router there is an "/" at the end or "/param" then after clicking on other link it adds extra word.

For example there 4 menu items

When to url https://foo.com/forecast add a "/" or some param "/2" then after clicking on other menu item except of Cash In Performance url will look like this (for example click on Monitor)

https://foo.com/forecast/newmonitor

But it should be https://foo.com/newmonitor

Steps to reproduce

  1. Go to the code on the sandbox (use link above)

  2. Click on "Cash in Forecast" link

    Url should be this https://myjn2170zp.codesandbox.io/forecast

  3. Then click on one of three forecasts.

    For example Forecast 1 and url should be this https://myjn2170zp.codesandbox.io/forecast/1

  4. After that click on Monitor link

    Url is like this https://myjn2170zp.codesandbox.io/forecast/newmonitor

    But it should be like this https://myjn2170zp.codesandbox.io/newmonitor

Word "forecast" is added to the url but it should not be like this.

Upvotes: 0

Views: 31

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

You need to set your initial links to have / at the beginning. Otherwise a link like href="something" always gets interpreted as go to "something" in the current folder. This is normal browser behaviour, it has nothing to do with react/react-router.

So use

const menuItems = [
  {
    key: 1,
    name: "Cash In Performance",
    icon: "itm_icon-insert_chart",
    link: "/"
  },
  {
    key: 2,
    name: "Cash in Forecast",
    icon: "itm_icon-turnover",
    link: "/forecast"
  },
  {
    key: 3,
    name: "Cash In List",
    icon: "itm_icon_list",
    link: "/cashinlist"
  },
  {
    key: 4,
    name: "Monitor",
    icon: "itm_icon-dvr",
    link: "/newmonitor"
  }
];

Edit Test React Router

Upvotes: 1

Related Questions