Adding a router for SPAs
Many modern single-page apps allow users to change pages without a page reload. Command AI 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 Command AI with .addRouter
. For example, you can supply a router to Command AI 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);
}, []);
};
When setting up your router, you might find the Extension helpful. You can open the Extension and do the following
- Go to Tools -> SDK Logs
- Ensure you are seeing your
.addRouter
call
Note that you only need to add a router once: after you’ve added it, that router can be used by any Command AI 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 Command AI at any given time.
Why aren't my pages using my router? I still see a page refresh.
Make sure that the Behavior for your page is set to Use router.