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
750 views
in Technique[技术] by (71.8m points)

reactjs - How to Implement dynamic routing in routes.js for generated menu items in sidebar in universal react redux boilerplate by erikras

I am currently working on a CMS based project.

For which i am using the universal react redux boilerplate by erikras

I really need suggestions on handling dynamic routing

Lets take a simple scenario form the boilerplate...

In routes.js

<Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>

data.js

export const data = [
  {id: 1, property: 'Dashboard', link: '/'},
  {id: 2, property: 'Login', link: '/login'},
  {id: 3, property: 'About Us', link: '/About'},
];

now, let say on the basis of user role, the properties in json data will change

let say new property: is

{id: 4, property: 'test page', link: '/test'}

When react will render the components, how it would know the route link .. as it is not defined in the routes.js

I am not getting the right way to implement it

We need a sidebar made of specific menu content as per the user role .

Let say we are building a reservation system , there can be different user roles like admin, maintenance mode, assistant role .

So different role will have different properties, accordingly we need to generate the menu on the basis it, as the properties will definitely differ as per user role.

Thanks!!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It is not clear from your example which component should be rendered for /test url? I suppose it is value of property key, right?

First option

You can do is something like this:

<Route path="/:page" component={Page}/>

It will allow you to render Page component for each url, that starts from / and this component will have page url inside this.props.routeParams.page. It allows you to find needed component inside Page#render:

render() {
  const url = this.props.routeParams.page;
  const PageComponent = data.find(page => page.link === url).property;
  render <PageComponent />;
}

Second option

You can generate Routes dynamically, but I'm not sure if it works (you can check it). You just should replace this part:

<Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>

with

 data.map(page => <Route path={page.link} component={page.property} key={page.id}/>)

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

...