A component to simplify the usage of react-router-dom, like the config of vue-router
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
-
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')
);
- If you want to Use in TypeScript , refer to use in TypeScript
- a part of route config
[
{
path: "/parent",
component: Parent,
children: [
{
path: "child1",
component: Child1
}
]
}
]
- Parent.jsx
const Parent = (props) => {
return (
<>
{props.children}
</>
)
}
- 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}
</>
)
}