Home > Back-end >  React router does not reload component if same element is used for two paths
React router does not reload component if same element is used for two paths

Time:06-05

I have the following two paths set up

          <Route path="bookings/:bookingnumber" element={<Bookings />} />
          <Route path="bookings" element={<Bookings />} />

In Bookings component I have conditional code written to check if a parameter :bookingnumber is passed, and then it only shows results relevant to that booking number. Otherwise, if no parameter is passed, it shows all the results for all the bookings.

I am using Outlet to display these components in the main area, and the two paths can be chosen from a sidebar.

Let's say I have 10 results if I go to /bookings, and 2 results if I go to /bookings/123.

However, if I go to /bookings/123 first and then to /bookings it keeps on showing only 2 results (the component does not reload, however I can see the URL changing in the browser)

CodePudding user response:

<Route path="bookings" element={<BookingList />}>
  <Route path=":bookingnumber" element={<ViewBooking />} />
</Route>

make two pages, first one will show all list of bookings and second one will show ID data

CodePudding user response:

Hello I believe you are using react-router-dom v6, in this case you can wrap the child routes inside your main path route. And then give them the index(true|false) attribute to make sure the router understand if it is the exact index page or should render a page based on params.

Note: I copied the example from above, and added some lines to fix it!

<Route path="bookings">
  <Route index={false} path=":bookingnumber" element={<ViewBooking />} />
  <Route index={true} element={<BookingList />} />
</Route>

UPDATE: You can handle a single component route with useParams hook.

Here what you're routing file should look like:

<Route path="bookings">
  <Route index={false} path=":bookingnumber" element={<ViewBooking />} />
  <Route index={true} element={<BookingList />} />
</Route>

And this is what your component should look like:

const MyComponent = () => {

  const { bookingnumber } = useParams()
  
  // if the path doesn't include the booking number then we should just render a normal page
  if( !bookingnumber ) {
    return <h1>This is a simple page</h1>
  }
  
  
  // if the page path does include the booking number then we can fetch data and return another result
  // example you can fetch data based on this number
  const [username, setUsername] = useState("")
  useEffect(() => {
    const fetchData = async () => {
      const req = await fetch(`https://629c770de9358232f75b55dc.mockapi.io/api/v1/users/${bookingnumber}`)
      const data = await req.json()
      setUsername(data.name)
    }
    fetchData()
  }, [username])

  return (
    <h1>Welcome mr.{username}</h1>
  )
}

  • Related