Skip to main content

addRouter(routerFn)

Sets a router function that pages can use to update the page's URL without triggering a reload. To learn more about using addRouter, see our section about adding a router for SPAs.

Example

React Router v5

import { useHistory } from "react-router";

const MyComponent = () => {
const history = useHistory();

React.useEffect(() => {
const routerFunc = (newUrl) => history.push(newUrl);
window.CommandBar.addRouter(routerFunc);
}, []);
};

React Router v6

import { useNavigate } from "react-router-dom";

const MyComponent = () => {
let navigate = useNavigate();

React.useEffect(() => {
const routerFunc = (newUrl) => navigate(newUrl);
window.CommandBar.addRouter(routerFunc);
}, []);
};

Custom router

// Example of a more complex router function which falls back to opening a new tab for specific routes
// this illustrates that you are not bound to using a specific framework but can use any custom logic you need
import { useHistory } from 'react-router';

const MyComponent = () => {
const history = useHistory();

React.useEffect(() => {
const routerFunc = (newUrl: string) => {
const isDocRoute = newUrl.startsWith('/docs');
if (isDocRoute) {
window.open(`https://www.command.ai${newUrl}`);
} else {
history.push(newUrl);
}
};

window.CommandBar.addRouter(routerFunc);
}, []);
};

Method parameters

routerFn Required

function

The router function. It should accept the following arguments:

PropertyTypeDescription
url RequiredstringThe url to navigate to