Skip to main content

@ones-op/router(deprecated)

DEPRECATED

This package is deprecated, please use the "react-router-dom" instead. Before replacing "@ones-op/router", please make sure to read the document about the configuration "enableMemoryRouter" and set it to true.

We provide a set of front-end routing component library that can use this library to operate the URL of the current page.

Requirements​

ONES
v3.6.25+

Installation​

Install the package in the plugin /web directory using the following command:

npm install @ones-op/router

Usage​

import { OPHashRouter } from '@ones-op/router'

ReactDOM.render(
<OPHashRouter>
<App />
</OPHashRouter>,
document.getElementById('root'),
)

Components​

The exported standard React Component usage API, the specific parameters are shown in the following:

OPHashRouter​

Provide a unified global routing configuration for the plugin, and wrap it in the periphery of the root component (such as ReactDOM.render()) to take effect once.

Props​

ParamsDescriptionTypeRequiredDefault
basenameBasic URL in all locationsstringN
windowThe window that needs to be tracked by the URLWindowNwindow

Examples​

import { OPHashRouter } from '@ones-op/router'

ReactDOM.render(
<OPHashRouter>
<App />
</OPHashRouter>,
document.getElementById('root'),
)

A OPLink is an element that lets the user navigate to another page by clicking or tapping on it. In react-router-dom, a OPLink renders an accessible a element with a real href that points to the resource it's linking to. This means that things like right-clicking a OPLink work as you'd expect. You can use reloadDocument prop to skip client side routing and let the browser handle the transition normally (as if it were an a href).

Props​

ParamsDescriptionTypeRequiredDefault
toDestination routestringY
reloadDocumentSkip client routebooleanN
replaceReplace the current route in the routing stackbooleanN
stateParameters carried when routing jumpobjectN

Examples​

import { OPLink } from '@ones-op/router'

function UsersIndexPage({ users }) {
return (
<div>
<h1>Users</h1>
<ul>
{users.map((user) => (
<li key={user.id}>
<OPLink to={user.id}>{user.name}</OPLink>
</li>
))}
</ul>
</div>
)
}

OPNavigate​

A OPNavigate element changes the current location when it is rendered. It's a component wrapper around useOPNavigate, and accepts all the same arguments as props.

Props​

ParamsDescriptionTypeRequiredDefault
toCompared to the parse of the parent route (no need to start from /)stringY
replaceIf the URL has not changed, whether to replace or increase the operation (replace or push)booleanN
stateParameters carried when routing jumpobjectN

Examples​

import { OPNavigate } from '@ones-op/router'

class LoginForm extends React.Component {
state = { user: null, error: null }

async handleSubmit(event) {
event.preventDefault()
try {
let user = await login(event.target)
this.setState({ user })
} catch (error) {
this.setState({ error })
}
}

render() {
let { user, error } = this.state
return (
<div>
{error && <p>{error.message}</p>}
{user && <OPNavigate to="/dashboard" replace={true} />}
<form onSubmit={(event) => this.handleSubmit(event)}>
<input type="text" name="username" />
<input type="password" name="password" />
</form>
</div>
)
}
}

A OPNavLink is a special kind of OPLink that knows whether or not it is active. This is useful when building a navigation menu such as a breadcrumb or a set of tabs where you'd like to show which of them is currently selected.

Props​

ParamsDescriptionTypeRequiredDefault
toDestination routestringY
caseSensitiveDecides whether to match in a case-sensitive mannerbooleanNfalse
childrenReact childrenReact.ReactNode|((props: { isActive: boolean }) => React.ReactNode)N
classNameCSS classstring|((props: { isActive: boolean }) => string|undefined)N
endWhen the descendant path is matched, make sure that the component will not be displayed as selectedbooleanN
styleInline stylesReact.CSSProperties|((props: { isActive: boolean }) => React.CSSProperties)N

Examples​

import { OPNavLink } from '@ones-op/router'

function NavList() {
let activeStyle = {
textDecoration: 'underline',
}

let activeClassName = 'underline'

return (
<nav>
<ul>
<li>
<NavLink to="messages" style={({ isActive }) => (isActive ? activeStyle : undefined)}>
Messages
</NavLink>
</li>
<li>
<NavLink
to="tasks"
className={({ isActive }) => (isActive ? activeClassName : undefined)}
>
Tasks
</NavLink>
</li>
<li>
<NavLink to="tasks">
{({ isActive }) => (
<span className={isActive ? activeClassName : undefined}>Tasks</span>
)}
</NavLink>
</li>
</ul>
</nav>
)
}

OPOutlet​

An OPOutlet should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.

Examples​

import { OPOutlet, OPRoute, OPRoutes } from '@ones-op/router'

function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<OPOutlet />
</div>
)
}

function App() {
return (
<OPRoutes>
<OPRoute path="/" element={<Dashboard />}>
<OPRoute path="messages" element={<DashboardMessages />} />
<OPRoute path="tasks" element={<DashboardTasks />} />
</OPRoute>
</OPRoutes>
)
}

OPRoute​

Rendering content based on the current position. Can be nested and rendered the sub-routing.

Props​

ParamsDescriptionTypeRequiredDefault
caseSensitiveDecides whether to match in a case-sensitive mannerbooleanNfalse
childrenUsed to rendering sub-routingReactNodeN
elementUsed to rendering UIReactNodeN<OPOutlet />
indexIf no match is found, the index route is displayedbooleanN
pathIt is used to match the current url, and the element of the rendering of element is successfulstringN

Examples​

import { OPRoutes, OPRoute } from '@ones-op/router'

;<OPRoutes>
<OPRoute path="/" element={<Dashboard />}>
<OPRoute path="messages" element={<DashboardMessages />} />
<OPRoute path="tasks" element={<DashboardTasks />} />
</OPRoute>
<OPRoute path="about" element={<AboutPage />} />
</OPRoutes>

OPRoutes​

Rendered anywhere in the app, OPRoutes will match a set of child OPRoutes from the current location.

Props​

ParamsDescriptionTypeRequiredDefault
childrenReact childrenReactNodeN
locationUsed for matching sub-elementsstringN

Examples​

import { OPRoutes, OPRoute } from '@ones-op/router'

;<OPRoutes>
<OPRoute path="/" element={<Dashboard />}>
<OPRoute path="messages" element={<DashboardMessages />} />
<OPRoute path="tasks" element={<DashboardTasks />} />
</OPRoute>
<OPRoute path="about" element={<AboutPage />} />
</OPRoutes>

Hooks​

The exported standard React Hooks usage API, the specific parameters are shown in the following:

useOPHref​

The useOPHref hook returns a URL that may be used to link to the given to location.

Params​

ParamsDescriptionTypeRequiredDefault
toDestination routestringN

Returns​

DescriptionType
The URL returned according to tostring

Examples​

import { useHref } from '@ones-op/router'

const StyledLink = styled('a', { color: 'fuchsia' })

const Link = React.forwardRef(({ to, ...rest }, ref) => {
let href = useHref(to)

return <StyledLink {...rest} href={href} ref={ref} target={target} />
})

useOPLocation​

The useOPLocation hook returns the current location object. This can be useful if you'd like to perform some side effect whenever the current location changes.

Returns​

DescriptionType
Current location informationLocation

Types​

interface Location {
state: unknown
key: Key
}

Examples​

import { useOPLocation } from '@ones-op/router'

function App() {
let location = useOPLocation();

React.useEffect(() => {
ga('send', 'pageview');
}, [location]);

return (
// ...
);
}

useOPRoutes​

The useOPRoutes hook is the functional equivalent of OPRoutes, but it uses JavaScript objects instead of OPRoutes elements to define your routes. These objects have the same properties as normal OPRoutes elements, but they don't require JSX.

The return value of useRoutes is either a valid React element you can use to render the route tree, or null if nothing matched.

Params​

ParamsDescriptionTypeRequiredDefault
routesRouter object arrayRouteObject[]Y
locationLocation informationLocation|stringN

Returns​

DescriptionType
Route ComponentReactNode

Examples​

import { useOPRoutes } from '@ones-op/router'

function App() {
let element = useOPRoutes([
{
path: '/',
element: <Dashboard />,
children: [
{
path: 'messages',
element: <DashboardMessages />,
},
{ path: 'tasks', element: <DashboardTasks /> },
],
},
{ path: 'team', element: <AboutPage /> },
])

return element
}

useOPParams​

The useOPParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the OPRoute path.

Returns​

DescriptionType
An object of key/valueReadonly<Params<K>>

Examples​

import { useParams } from '@ones-op/router'
function ProfilePage() {
let { userId } = useParams();
// ...
}

function App() {
return (
<OPRoutes>
<OPRoute path="users">
<OPRoute path=":userId" element={<ProfilePage />} />
<OPRoute path="me" element={...} />
</OPRoute>
</OPRoutes>
);
}

useOPNavigate​

The useOPNavigate hook returns a function that lets you navigate programmatically, for example after submitting the form.

Returns​

DescriptionType
Navigate functionNavigateFunction

Types​

interface NavigateFunction {
(to: To, options?: { replace?: boolean; state?: any }): void
(delta: number): void
}

Examples​

import { useOPNavigate } from '@ones-op/router'

function SignForm() {
let navigate = useOPNavigate()
async function handleSubmit(event) {
event.preventDefault()
await submitForm(event.target)
navigate('../success', { replace: true })
}

return <form onSubmit={handleSubmit}>{/* ... */}</form>
}

useMatch​

Returns match data about a route at the given path relative to the current location.

Params​

ParamsDescriptionTypeRequiredDefault
patternRouter object arrayPathPattern<Path>|PathY

Returns​

DescriptionType
Matched dataPathMatch<ParamKey>|null

Types​

interface PathPattern<Path extends string = string> {
path: Path
caseSensitive?: boolean
end?: boolean
}

interface PathMatch<ParamKey extends string = string> {
params: Params<ParamKey>
pathname: string
pattern: PathPattern
}