react-router-control

A component to simplify the configuration of react-router-dom, like the configuration of vue-router

Usage no npm install needed!

<script type="module">
  import reactRouterControl from 'https://cdn.skypack.dev/react-router-control';
</script>

README

react-router-control

A component to simplify the usage of react-router-dom, like the config of vue-router

Installation

To use react-router-control with your React app, install it as a dependency:

# If you use npm:
npm install react-router-control

# Or if you use Yarn:
yarn add react-router-control

Quick Start

  • At first , we recommend that you use separate files to manage your config. If you are an experience with vue-router , the config is basically the same as it. Or you can refer to routes.js.

  • Now , import your config (routes.js) at main.js:

//main.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from "react-router-dom";
import RouterControl from "react-router-control";

import routes from "xxx/routes" //your config

ReactDOM.render(
    <BrowserRouter>
        <RouterControl routes={routes}/>
    </BrowserRouter>,
    document.getElementById('root')
);

Reference

1、render route children

  • a part of route config
[
    {
        path: "/parent",
        component: Parent,
        children: [
            {
                path: "child1",
                component: Child1
            }
        ]
    }
]
  • Parent.jsx
const Parent = (props) => {
    return (
        <>
            {props.children}
        </>
    )
}

2、get dynamic segment in component

  • a part of route config
[
    {
        path: "/dynamic/:type",//dynamic segment 'type'
        component: Dynamic
    }
]
  • Dynamic.jsx
// in class component
import React, {Component} from "react"

class Dynamic extends Component {
    constructor(props) {
        super(props)
        //use props
        const {type} = props.match.params
        console.log(type)
    }

    render() {
        return (
            <div>test</div>
        )
    }
}
// in function component
import {useParams} from "react-router-dom"

const Dynamic = (props) => {
    // use hooks
    const {type} = useParams();
    console.log(type)

    return (
        <>
            {props.children}
        </>
    )
}