react-router-dom-view

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 reactRouterDomView from 'https://cdn.skypack.dev/react-router-dom-view';
</script>

README

react-router-dom-view

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

Installation

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

# If you use npm:
npm install react-router-dom-view

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

Usages

1、routes config

If you are an experience with Vue.js , the configuration is basically the same as it. Or you can refer to the following configuration.

//examples
const routes = [
    {
        path: "/home",
        component: () => <div>home</div>,
    },
    {
        path: "/about/:type",//dynamic segment 'type'
        component: () => <div>about</div>
    },
    {
        path: "/user",
        component: User,
        children: [
            { //if matching "/user", router will jump to "/user/profile".

                path: "", //or use absolute path "/user"
                redirect: "profile" //or use absolute path "/user/profile"
            },
            {
                path: "profile", //or use absolute path  "/user/profile"
                component: () => <div>profile</div>,
            },
            //and more……
        ]
    }
];
note:If you use an absolute path, you must use the full path

2、render routes

import React from 'react';
import ReactDOM from 'react-dom';
import RouterView from "react-router-dom-view";

import routes from "routes.js" //导入路由配置

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

2、render route children

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

4、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}
        </>
    )
}