0

I am having a responsive react Web-Application where i need a specific route only for the case of mobile that is if the device width is less than something for example 'x' but all the routes have been created in the same file something like:

<BrowserRouter>
<Switch>
  <Route exact path='/login/' component={Login} />
  <Redirect exact from='/' to='/login/' />
  <Route exact path='/sample/' component={sample} />
</Switch>

so the route is now accessible from devices with dimensions of more than 'x' width also how can i make the route available based on device width or how can i block a specific route based on device dimensions.

aravind_reddy
  • 5,236
  • 4
  • 23
  • 39
  • You can make use of Higher Order Component just like in the post https://stackoverflow.com/questions/31084779/how-to-restrict-access-to-routes-in-react-router Here they are checking if the user is logged in. You can try similar and check the device width.. – pritesh Dec 26 '17 at 06:10

1 Answers1

1

For selective routing, you can put a check in your route render function. Here's an example:

class Example extends Component{
    constructor(props){
        super(props);

        this.check = this.check.bind(this);
    }

    check(){
        var w = window,
        d = document,
        e = d.documentElement,
        g = d.getElementsByTagName('body')[0],
        windowWidth = w.innerWidth || e.clientWidth || g.clientWidth; //window width

        return windowWidth > 568; //returns true for widths larger than 568 pixels
    }

    render(){
        return(
            <Router>
                <Route path='/example' render={() => {
                    if(this.check()) return <Child />; 
                    else return <OtherChild />;
                }}/>
            </Router>
        )
    }
}
raksheetbhat
  • 850
  • 2
  • 11
  • 25