score:5

Accepted answer

try the render function prop instead of component prop of route. something like this:

<route render={props => {
  // look for some param in the query string...
  const usecomponenta = querystringcontains('a');
  if(usecomponenta) {
    return <componenta {...props}/>;
  } else {
    return <componentb {...props}/>;
  }
}}/>

score:5

there are 2 ways to do that:

1) use location.search in react component to get the query string, then pass it to child component to prevent re-rendering the whole component. react-router has the official example about this.

2) define a regex path of router to catch the query string, then pass it to react component. take pagination as an example:

routes.js, for router config you can refer this

const routerconfig = [
  {
    path: '/foo',
    component: 'foo',
  },
  {
    path: '/student/listing:pagenumber(\\?page=.*)?',
    component: 'student'
  },

student.js

  render() {
    // get the page number from react router's match params
    let currentpagenumber = 1;
    // defensive checking, if the query param is missing, use default number.
    if (this.props.match.params.pagenumber) {
      // the match param will return the whole query string, 
      // so we can get the number from the string before using it.
      currentpagenumber = this.props.match.params.pagenumber.split('?page=').pop();
    }
    return <div> 
             student listing content ...
             <pagination pagenumber = {currentpagenumber}> 
           </div>
  }

pagination.js

render() {
    return <div> current page number is {this.props.pagenumber} </div>
  }

the 2nd solution is longer but more flexible. one of the use cases is server sider rendering:

apart from the react components, the rest of the application (e.g. preloaded saga) need to know the url including query string to make api call.


Related Query

More Query from same tag