0.1.9 • Published 4 years ago

sev-react-redux-router v0.1.9

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
4 years ago

sev-react-redux-router

sev-react-redux-router is a router for react and redux. It is easy to use. it can switch views in both parallel and interdependent. We have programmed a router that is precisely adapted to our application. This router however is not intended for seo sites.

Example

Getting started

Installation

The best way to consume sev-react-redux-router is via the npm package which you can install with npm (or yarn if you prefer).

npm install sev-react-redux-router --save

To use sev-react-redux-router, you need the following packages too:

npm install history redux react-redux qs --save

How to use it

Easy set up and routing

The following implementation is only an example. It is no problem in case you have built redux differently, you then just have to add the router reducer to the store.

The examples are taken from this page. If you need more information, check the repository.

index.js

import ReactDOM from "react-dom";
import {createStore, applyMiddleware} from "redux";
import {Provider} from "react-redux";
import {combineReducers} from "redux";
import {routerReducer, Router, Route} from "sev-react-redux-router";
import Home from "./pages/Home/Home";
import Contributors from "./pages/Contributors/Contributors";
import NotFound from "./pages/NotFound/NotFound";

const reducers = combineReducers({
    //other reducers
    router: routerReducer,
});
const store = createStore(
    reducers,
    //middleware
);

ReactDOM.render(
    <Provider store={store}>
        <Router>
            <Route path="/" exact component={Home}/>
            <Route path="/contributors" component={Contributors}/>
            <Route path="/*" component={NotFound}/>
        </Router>
    </Provider>,
    document.getElementById('root'),
)

Parallel and nested routes

Nested routes can easily be specified in other components. With the sev-react-redux-router, however, paths must always be specified as absolute values.

In the following example you can find out how to connect routes in parallel. Components can exist simultaneously through an url.

./pages/Contributors/Contributors.js

import * as React from "react";

export default class Contributors extends React.Component {
    render() {
        return (
            <div className='Contributors'>
                <Route path={'/contributors'} component={ContributorsList}/>
                <Route path={'/contributors/:contributorsId'} component={ContributorsDetails}/>
            </div>
        );
    }
}

How to get route data into the component?

Please note that this._isMounted is only taken because we work with component state. Normally redux is used and this._isMounted is not necessary. If you want more information about this._isMounted you can find it here.

However, it is important to know that if a component depends on a route parameter, and the parameter changes, the component will be remounted.

./pages/ContributorsDetails/ContributorsDetails.js

import * as React from "react";
import ContributorsService from "../../services/ContributorsService";
import {connect} from "react-redux";

class ContributorsDetails extends React.Component {
    _isMounted: boolean = false;
    state = {
        contributor: {}
    };

    async componentDidMount(): void {
        const {router}= this.props;
        this._isMounted = true;
        try {
            const contributor = await ContributorsService.getContributor(
                router.current.params.contributorsId
            );
            this._isMounted && this.setState({contributor});
        } catch (e) {
            //Errorhandling ...
        }
    }

    componentWillUnmount(): void {
        this._isMounted = false;
    }

    render() {
        const {contributor = {}} = this.state;
        return (
            <div className="ContributorsDetails">
                <h2>{contributor.name}</h2>
                <p>{contributor.description}</p>
            </div>
        );
    }
}

const mapStateToProps = (state) => state;
export default connect(mapStateToProps)(ContributorsDetails);

Here is a overview of the data we get from the store.
console.log(this.props.router)

{
    "prev": {
        "pathname": "/contributors",
        "search": "",
        "searchObject": {},
        "params": {},
        "hash": ""
    },
    "current": {
        "pathname": "/contributors/0",
        "search": "",
        "searchObject": {},
        "params": {
            "contributorsId": "0"
        },
        "hash": ""
    },
    "routes": [
        {
            "path": "/",
            "id": "511cea53-...",
            "exact": true
        }, {
            "path": "/contributors",
            "id": "55a989aa-..."
        }, {
            "path": "/supporter",
            "id": "16b5a72b-..."
        }, {
            "path": "/license",
            "id": "3d9dce34-..."
        }, {
            "path": "/contributors",
            "id": "0243cc0b-..."
        }, {
            "path": "/contributors/:contributorsId",
            "id": "209ec23c-..."
        }
    ]
}

If you separate params with commas, you get an array

{
   "prev": {...},
    "current": {
        "pathname": "/contributors/0,1",
        "search": "",
        "searchObject": {},
        "params": {
            "contributorsId": ["0", "1"]
        },
        "hash": ""
    },
    "routes": [...]
}

Redirects

Redirects from one path to another.

<Redirect from="/somewhere" to="/contributors"/> //#/somewhere -> #/contributors
<Redirect from=">/somewhere/:id" to="/contributors/:id"/> //#/somewhere/0 -> #/contributors/0
<Redirect from=">/*" to="/"/> //#/somewhere/in/neverland -> #/

Navigation

Navigating with a normal link looks like this:

<a href="/contributors">Contributors</a>
<a href={'/contributors/' + value}>Contributors Details</a>

Programatically you can call the push function via sev-react-redux-router.

import {push} from 'sev-react-redux-router';

push('/contributors')
push('/contributors/' + value) //or

There is also a function of sev-react-redux-router that checks if the path is correct.

import {isRouteActive} from 'sev-react-redux-router';

//URL is #/contributors/0

console.log(isRouteActive("/contributors")); //true
console.log(isRouteActive("/contributors/0")); //true
console.log(isRouteActive("#/contributors/0")); //true

console.log(isRouteActive("/")); //false -> because in this example is linked with a exact route. otherwise would be true
console.log(isRouteActive("/contributors/1")); //false
console.log(isRouteActive("/license")); //false

Lazy loading route

In combination with React.lazy and Suspense lazy loading is simple.

import React, {Suspense} from 'react';
import Loader from "./components/Loader/Loader";
...

const License = React.lazy(() => import('./pages/License/License'));

ReactDOM.render(
    <Provider store={store}>
    	<Suspense fallback={<Loader />}>
            <Router>
                ...
                <Route path="/license" component={License}/>
            </Router>
        </Provider>
    </Provider>,
    document.getElementById('root'),
);
0.1.9

4 years ago

0.1.8

4 years ago

0.1.7

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.4

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago