0

Component is loaded on the correct path like /characters/kabal -- (kabal it`s ID)

But its loaded if you just enter any text after /characters/ for example /characters/548fnufndf or /characters/548fnufndf/dnbsdnhdj/dfmd

How to check the correct path in a functional component before loading the component and, if the path is wrong, redirect to another page?

//App.js
          <Switch>
              <Route
                path="/characters"
                exact
                component={Characters}/>
              <Route
                exect
                path="/characters/:id"
                render={(props) => <CharacterPage {...props}/>}
              />
              <Route
              exect
                path="/settings"
                component={Settings}/>}
                />
              <Route exect insecure component={Error} />
        </Switch>


//Link to component and array of IDs
 const item = [
    {charId:'fujin'},
    {charId:'scorpion'},
    {charId:'kabal'}
]

    <Link
        exact="true"
        to={{
          pathname:`/characters/${item.charId}`,
        }}
    </Link>
    
//A component that should be loaded only if a link with this id exists.

  const Scrollable = ({match}) => {
      useEffect(() => {
         let id = data[match.params.id]
          if(!id) {
             return <Redirect to="/" />
          }
  }, [])
  }
Dio
  • 245
  • 3
  • 15

1 Answers1

0

What version of React-router are you using?

Here's a similar question: React-Router: No Not Found Route?

In summary

If you're using v4 or v5 then:

Keep the path (url stays unchanged)

<Switch>
    <Route exact path="/users" component={MyComponent} />
    <Route component={GenericNotFound} />
</Switch>

Redirect to another route (change url)

<Switch>
    <Route path="/users" component={MyComponent} />
    <Route path="/404" component={GenericNotFound} />
    <Redirect to="/404" />
</Switch>

Pay attention to the order as well, NotFoundComponent must be last for that path. Also like what @cbr said, exect should be exact.

  • I use 5.2. I have a problem with `id`, you can enter any `id` in browser address bar and the component will still be loaded, although it should only be loaded if the correct `id` is entered. Perhaps if you try it yourself it will be clearer https://mrrjdio.github.io/ to enter, you can enter any password and mail and click register – Dio Aug 13 '21 at 19:02
  • try to enter https://mrrjdio.github.io/characters/scorpion and then incorrectly https://mrrjdio.github.io/characters/gjdhb/jndnb – Dio Aug 13 '21 at 19:06
  • The sign in page doesn't seem to be working correctly and both dynamic routes sent me to a 404 page -- so the issue is that if you do /characters/scorpion it loads the scorpion component, but if you do /characters/*/* it still loads the scorpion component? Did correcting the `exect` to `exact` have any effect? – Jordan Schneider Aug 15 '21 at 01:44