Discussion about using useRouter and hooks for programmatic navigation in Sanity.io

4 replies
Last updated: Jul 17, 2023
Hey peeps I'm struggling to find information on the 'useRouter','usePaneRouter' and/or hooks, I think I need them to navigate a user programmatically to a new document. There are few old chats here discussing this, but all seem to relate to v2?
Jul 17, 2023, 10:28 PM
👋 We don’t have that documented for V3, but here’s an example from a previous thread:
Jul 17, 2023, 10:31 PM
import {definePlugin} from 'sanity'
import {route, useRouter} from 'sanity/router'
import {useEffect} from 'react'
import {Box, Button} from '@sanity/ui'

const PATHS = ['view-1', 'view-2']

function MyTool() {
  const router = useRouter()

  // Set the default path if no path is set or if the path is not valid
  useEffect(() => {
    if (!PATHS.includes(router.state.path as string)) {
      router.navigate({path: PATHS[0]})
    }
  }, [router])

  return (
    <div>
      {PATHS.map((path) => (
        <Button
          key={path}
          mode="ghost"
          onClick={() => router.navigate({path})}
          selected={router.state.path === path}
          text={path}
        />
      ))}

      <Box padding={4}>
        {router.state.path === PATHS[0] && <div>View 1</div>}
        {router.state.path === PATHS[1] && <div>View 2</div>}
      </Box>
    </div>
  )
}

export const toolWithRouting = definePlugin({
  name: 'my-tool',
  tools: [
    {
      component: MyTool,
      name: 'my-tool',
      router: route.create('/', [route.create('/:path')]),
      title: 'Tool',
    },
  ],
})
Jul 17, 2023, 10:31 PM
Thanks for the speedy reply, I'll take what you've provided and see how far I get 🙏
Jul 17, 2023, 10:35 PM
let us know if you need more help with implementation.
Jul 17, 2023, 10:52 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?