Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router path validation and redirection

I'm using react-router with react-router-redux for implementation of SPA. I want to implement such a UI:

simple UI schema

The main idea that I have a list of Entitnes and if I click on an Entity, url is changed from http://domain/entities to http://domain/entities/id, where id is an Entitiy's id and the specific React component is loaded.

For performing navigation I'm using push method from react-router-redux but also I can just type a url path. But I need somehow validate url params. I want to check for id, is it in correct format and does the specific entity exist, and if not, I should rollback url to a previous state and then show an error alert.

I guess it is possible to do, but I'm a very beginner in React, so I would like to hear any advice from you.

Thanks in advance.

like image 279
Pavel Griza Avatar asked May 06 '16 14:05

Pavel Griza


1 Answers

Learn about react-router hooks like onEnter, etc. You can determine them in your routes.

https://github.com/ReactTraining/react-router/blob/v3/docs/Glossary.md#enterhook

Example:

var correctDataHandler = function(transition) {
    if( condition )
        transition.redirect('/')
};

var router = ReactDOM.render((
    <Router history={ReactRouter.createMemoryHistory()}>
        <Route path="/" component={ AddressForm } />
        <Route path="/map-page" component={ Map } onEnter={ correctDataHandler } />
        <Route path="/select-product-page" component={ CardsList } />
        <Route path="/login" component={ LoginRegisterPage } />
    </Router>
);
like image 95
Yurii Kramarenko Avatar answered Oct 10 '22 21:10

Yurii Kramarenko