Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

react-router render menu when path does not match

I'm using react-router and I want to render a menu component when the user is not in the root and not in the /login path. This is what I have so far

        <Route path="/:subpath" component={TopMenuComponent} />
        <div>
            <Route
                exact path="/"
                render={props => (
                    <LoginContainer {...props} setTitle={this.setTitle} />
                )}
            />               
            <Route path='/landing' component={LandingComponent} />
        </div>

takes care of not rendering the TopMenuComponent component in the '/' location, however how do I avoid it rendering TopMenuComponent when the user is in the /login path? I could always create another component and wrap it up, but I think that is too much just for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simplest Implementation

Use a ternary expression or short-circuit evaluation to conditionally render your component based on location.pathname, like so:

<Route 
    render={({ location }) => ['/', '/login'].includes(location.pathname)
        ? <Component/>
        : null
    }
/>

Regex Implementation

React Router's matching of path strings relies on path-to-regexp@^1.7.0.

As a result, you can instruct routes to not render for certain paths using regular expressions.

The following implementations should render given any path value, bar "/" and "/login":

// With Regex Inside String.
<Route path={"^(?!.*(/|/login)).*$"} component={TopMenuComponent}/>

// With Explicit Regex.
<Route path={new RegExp('^(?!.*(/|/login)).*$')} component={TopMenuComponent}/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...