Reputation: 1375
I use several route in my app And I have conditions for bringing information in that route. I created an array and the array values are created according to those conditions. Part of my code:
for (var i = 0; i < res.length; i++){
var arr = res[i];
switch (arr) {
case "MsgManagementTab":
routearray.push({path :"/main/messages" ,component:<Messages isSidebarActive={this.state.isSidebarActive} />})
break;
case "AlgorithmManagementTab":
routearray.push({path :"/main/algorithms",component:<Algorithm isSidebarActive={this.state.isSidebarActive}/>})
break;
case "SocialNetworkManagementTab":
routearray.push({path :"/main/socialNetworks",component:<SocialNetWork isSidebarActive={this.state.isSidebarActive}/>})
}
}
and :
<Switch>
{this.state.routearray ?this.state.routearray.map(item=>{
return <Route path={item.path}>{item.component}</Route>
</Switch>
In this case, for example, I have access to the Route of the message when the MsgManagementTab
exists.
What I want to do is if the MsgManagementTab
does not exist, and if the user wants to go to the page via URL, go to the path I want to be redirected to.
This is the path I want to redirected :
<Route path="/main/access/deny"><NoAccess isSidebarActive={this.state.isSidebarActive} /></Route>
Someone knows how to do this?
Upvotes: 1
Views: 1605
Reputation: 203457
If I understand your question/issue, you want the app to redirect from "/main/messages" to "/main/access/deny" when the Switch
isn't rendering the Route
for "/main/messages".
After the mapped routes include a Redirect
component to redirect from a specific path to another path. This works by allowing the Switch
to match the Route
for "/main/messages" first if it exists, otherwise since that route won't be available the Redirect
will handle it.
<Switch>
...
{this.state.routearray ? this.state.routearray.map(item => (
<Route path={item.path}>{item.component}</Route>
))}
...
<Redirect from="/main/messages" to="/main/access/deny />
...
<Route path="/main/access/deny">
<NoAccess isSidebarActive={this.state.isSidebarActive} />
</Route>
...
</Switch>
Upvotes: 2