React router path validation and redirection
Asked Answered
B

2

6

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.

Buffy answered 6/5, 2016 at 14:14 Comment(0)
B
8

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>
);
Boschvark answered 6/5, 2016 at 14:56 Comment(4)
Thanks! Exactly what I'm looking for!Buffy
And how to check state in onEnter? Can't figure this out.Trioecious
@vsync here is newer doc (for v3) https://github.com/ReactTraining/react-router/blob/v3/docs/Glossary.md#enterhookBoschvark
From react-router-v4 onEnter and similar properties have been removed. Migrating from v2/v3 to v4Cockswain
P
-1

Validation for login and router in ReactJs

if(this.state.username==="admin" && this.state.password==="1234567")
                    {
                        this.props.history.push("/Welcome");
                    }
Piapiacenza answered 25/3, 2021 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.