Search code examples
reactjsroutesreact-routerreact-router-redux

react router - pass props via url arguments


I am developing a multilingual and multi-currency app that uses react-router, react-router-redux & react-router-bootstrap for routing.

Currently users arrive at the app with a default language and currency however I'd like to be able to provide some arguments in the url to set either the language or currency - something along the lines of http://myapp.com/page1?lang='fr'

I'd also like to have the ability to use these arguments on any page, so that:

http://myapp.com/page1?lang='fr' and http://myapp.com/page2/example1/test?lang='ru' are both handled the same way. Basically I want the router to check for the presence of these arguments in any url that is passed to it, and if they are present execute a function.

I can't find any clear information about this in the documentation for react-router but I'm sure it's possible. Can anyone point me in the right direction?


Solution

  • You can access the query params via this.props.location.query.langs from inside the component also mentioned by @Lucas.

    I have provided a working example for better understanding.

    Apart from that In your scenario I will suggest you to look into onEnter hooks available in react router.

    let Router = ReactRouter.Router;
    let RouterContext = Router.RouterContext;
    let Route = ReactRouter.Route;
    let Link = ReactRouter.Link;
    
    function redirectBasedOnLang(nextState, replace) {
        // check nextState.location.query
        // and perform redirection or any thing else via
        console.log("called");
        console.log(nextState.location.query);
    }
    
    const Dashboard = (props) => {
      return (
        <b className="tag">{"Dashboard"}</b>
      );
    }
    
    FrDashboard
    
    const FrDashboard = (props) => {
      return (
        <div> 
             <h3> Dashboard </h3>
             <hr/>
            Primary language: {props.location.query.lang}
        </div>
      );
    }
     
    class App extends React.Component {
       
       render() {
         return (
          <div>
            <h2>App</h2>
    
            {/* add some links */}
            <ul>
          <li><Link to={{ pathname: '/dashboard', query: { lang: 'fr' } }} activeClassName="active">Dashboard</Link></li>
            </ul>
            <div>
            {this.props.children}
            </div>
          </div>
         )
       }   
    };
    
    App.contextTypes = {
      router: React.PropTypes.func.isRequired,
    };
    
    ReactDOM.render(<Router history={ReactRouter.hashHistory}>
        <Route path="/" component={App}>
              <Route path="dashboard" component={Dashboard} onEnter={redirectBasedOnLang} />
              <Route path="dashboardfr" component={FrDashboard} />
        </Route>
      </Router>, document.getElementById('test'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/3.0.0/ReactRouter.min.js"></script>
    
    
    <div id="test"></div>

    let Router = ReactRouter.Router;
    let RouterContext = Router.RouterContext;
    let Route = ReactRouter.Route;
    
    const Link = (props) => {
      return (
        <b className="lang" onClick={() => props.onClick(props.lang)}>{props.lang}</b>
      );
    }
          
    class App extends React.Component {
      
      constructor(props) {
        super(props);
        
        this.handleLang = this.handleLang.bind(this);
        this.state = { langs: [] };
      }
      
      handleLang(lang) {
        let langs = [].concat(this.state.langs);
        if(langs.indexOf(lang) != -1) {
          langs = langs.filter(item => item != lang);
        }
        else langs.push(lang);
        
        this.setState({langs: langs});
        
        this.context.router.push({
          pathname: '/',
          query: { langs: langs }
        });
      }
      
       render() {
    
         return (
          <div>
             <Link onClick={this.handleLang} lang={"fr "} />
             <Link onClick={this.handleLang} lang={"en "} />
             <Link onClick={this.handleLang} lang={"hi "} />
             
             <div>
               <hr/>
               <br/>
               active languague :
               <div>{this.props.location.query.langs ? [].concat(this.props.location.query.langs).join(',') : ''}</div>
             </div>
          </div>
         )
       }   
    };
    
    App.contextTypes = {
      router: React.PropTypes.func.isRequired,
    };
    
    ReactDOM.render(<Router history={ReactRouter.hashHistory}>
        <Route path="/" component={App} /> 
      </Router>, document.getElementById('test'));
    .lang {
      display: inline-block;
      background: #d3d3d3;
      padding: 10px;
      margin: 0 3px;
      cursor: pointer;
      width : 50px;
      border : 1px solid black;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/3.0.0/ReactRouter.min.js"></script>
    
    <div id="test"></div>