Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In react router 4, how does one negate a route / path using regex?

Say i have a route switch statement like the following:

render () {
    <pre>
        <Switch>
            <Route path="/foo" render={render}>
            <Route path="/bar" render={renderBar}>
            <Route path="/" render={renderHome}>

            {/* How do i express everything except the home page ?*/}

            <Route render={renderFourOhFour}>
        </Switch>
    </pre>
}

How do i write a route that excludes everything except the home page given the above example? Do i just write a regex? If so i've tried something like

path={^(?!.*(home))}

with the regex react router v4 tester: https://pshrmn.github.io/route-tester/#/

like image 941
chrisjlee Avatar asked Jul 26 '17 03:07

chrisjlee


2 Answers

You can use the render method on the Route, which gets passed the location as a prop. So:

<Route render={({location}) => {
  return location.pathname !== '/' ? <p>Not home</p> : ''
}} />
like image 103
Greg Avatar answered Oct 22 '22 14:10

Greg


1) It will be visible everywhere except /home

<Route path={/\/(?!home)/} component={Component} />

2) Everywhere except /

<Route path={/^.{2,}$/} component={Component} />
like image 42
Vladislav Zaynchkovsky Avatar answered Oct 22 '22 13:10

Vladislav Zaynchkovsky