React conditionally render a component in specific routes

孤人 提交于 2021-02-17 06:37:07

问题


This is my Index.js

ReactDOM.render(
   <React.StrictMode>
        <Provider store={store}>
            <Router>
               <App className="app-main" />
            </Router>
         </Provider>
    </React.StrictMode>,
  document.getElementById('root')
);

And here is App.jsx

<Switch>
     appRoutes.map(route =>
          <Route path={route.path} component={route.component} key={route.key}/>
     )}
</Switch>
<BottomNav />

I want to render the BottomNav component in specific routes in which they are some sub routes too. I used withRouter in the Bottom nav but its match is just a "/" and i have access to location only. Location is not enough for me because as i said there are some sub routes in those routes. So for example in a profile route i have activities and friends. i want render BottomNav in profile/friends but not in profile/activities how can i achieve this. My solution was to set current route path in redux and pass it to bottom nav and check if it's in valid routes i render bottom nav but i cant write and repeat a function hundered time in different views to when they mounted update current route in redux. I forgot to say i'm new to React pleas be gentle and explain in details tnx :)


回答1:


I haven't tested it, just brought it up from the top of my head. The idea is that you create a map of routes where your BottomNav should appear. Else, just return null.

import {withRouter} from 'react-router-dom'

const ROUTES_WITH_BOTTOM_NAV = {
   '/home': true,
   '/profile/friends': true
}

const BottomNav = (props) => {
   const currentPage = props.location.pathname;
   if (!ROUTES_WITH_BOTTOM_NAV[currentPage]) return null;

   return (...yourBottomNavJsx)
}

export const withRouter(BottomNav)

Let me know if that helped.



来源:https://stackoverflow.com/questions/64721310/react-conditionally-render-a-component-in-specific-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!