Joshua Bitton
Joshua Bitton

Reputation: 403

React router paths

So I'm trying to display a 404 page if the path in my web app is undefined or nothing is rendered due to something having been deleted. For example, users can create books and the books id becomes the path to that page. But if a user deletes that book, the path will be undefined. So, if that happens id like to be able to make sure that any other user that tries to go onto that page is shown a 404 message. For example, a link could be '/home/undefined' or '/undefined/books'

Upvotes: 1

Views: 155

Answers (2)

machineghost
machineghost

Reputation: 35725

To create any sort of "404 route", you simply have to add a route that matches any URL, and use it in a switch tag along with the valid routes. For instance:

<Switch>
  <Route path ="/home" component={Home} />
  <Route path ="/home/book" component={Book} />
  <Route path ="/" component={FourZeroFour} />
</Switch>

You can also achieve the same effect by not using a Switch, and instead using exact on every route except the final one:

<Route path ="/home" component={Home} exact />
<Route path ="/home/book" component={Book} exact />
<Route path ="/" component={FourZeroFour} />

But what if you have a route that potentially matches both invalid and valid URLS, for instance:

  <Route path ="/home/book/:bookId" component={SpecificBook} />

(where :bookId could be undefined)

In that case, you'll instead want to check the URL parameter's validity inside your component. For instance, your SpecificBook component might do the following:

const SpecificBook = ({ bookId } ) => {
  if (bookId === 'undefined') return <Redirect to="/404" />;
  // rest of component
}

You could also use history.push, but the Redirect tag will do more than just add a history entry; it will simulate a (server-side) redirect.

Upvotes: 1

Vo Quoc Thang
Vo Quoc Thang

Reputation: 1396

I will check the book_id first and the redirect if not found.

import {useHistory} from "react-router-dom"

function App() {

   const history = useHistory();
 
   if (!bookId) {
     history.push("/404");
     return null;
   }
   return <></>
}

Upvotes: 1

Related Questions