Skip to main content

Adding a router for SPAs

Many modern single-page apps allow users to change pages without a page reload. CommandBar supports reload-less routing by allowing you to supply a router function.

If your site uses routing this way, you should supply a router function to CommandBar with .addRouter. For example, you can supply a router to CommandBar like this:

// React-Router v6 example
import { useNavigate } from "react-router-dom";

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

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

Note that you only need to add a router once: after you’ve added it, that router can be used by any CommandBar experience.

Within your router function, you can then use whatever routing library you're using to route the user. For more on adding a router, visit our SDK docs for .addRouter().

Adding multiple routers

As of right now, only a single router function can be loaded into CommandBar at any given time.