Max Bunker
Max Bunker

Reputation: 187

React Router redirect when url isn't correct

Can you help me!

I'm stuck with url pameters. When I type http://localhost:3000/#/willmatch/sdf , then I got redirected. It's great, that's what I want. But when http://localhost:3000/#/willmatch111/ , nothing is happening.

Is it possible to get redirected when url isn't correct?

I've tried to enter http://localhost:3000/#/willmatch1 , but I stay on WillMatch, but I want to get NoMatch if url isn't correct

import React, { Component } from 'react';
import { HashRouter as Router, Switch, Route, Link, Redirect } from 'react-router-dom';

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/willmatch">Will Match</Link></li>
            <li><Link to="/will-not-match">Will Not Match</Link></li>
            <li><Link to="/also/will/not/match">Also Will Not Match</Link></li>
          </ul>

          <Switch>
            <Route path="/" exact component={Home} />
            <Route exact path="/:id" component={WillMatch} />
            {/* <Route component={NoMatch} /> */}
            <Redirect to="/" />
          </Switch>
        </div>
      </Router>
    );
  }
}

function Home() {
  return <h1>Home</h1>
}

function WillMatch({ match }) {
  return <h1>{match.params.id}</h1>
}

function NoMatch() {
  return <h1>NoMatch}</h1>
}

export default App;

Upvotes: 1

Views: 8211

Answers (3)

theUtherSide
theUtherSide

Reputation: 3476

It looks like it's thinks maybe it thinks willmatch is :id. I have one working like:

<Switch>
    <Route path="/" exact component={Home} />
    <Route path="/:id" component={WillMatch} />
    <Route path="/notfound" exact component={NoMatch} />
    <Redirect to="/notfound" />
</Switch>

You could also try:

    <Route path="/thing/:id" component={WillMatch} />

A similar example is provided here:

https://reacttraining.com/react-router/web/example/no-match

A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches

Upvotes: 4

UjinT34
UjinT34

Reputation: 4977

Try <Route exact strict path="/:id" component={WillMatch} />

/:id is a placeholder and it matches everything. Without strict it matches /whatever and /whatever/. With strict it matches only /whatever.

You either need to list all valid paths or check props.match.params.id inside WillMatch component and redirect if it is not valid.

Upvotes: 1

Jacob Bralish
Jacob Bralish

Reputation: 271

You should be able to place something like this at the bottom of your Routes, make sure it's at the bottom or else it will match every route. It will redirect if the route isnt found among the rest!

Upvotes: 0

Related Questions