Say that you’ve built a <ListItem>
component with styled-components. You’d like to make the whole item behave as a link — and you also want to highlight the item when the link points to the current page.
You can use Navi’s useActive()
hook to check whether the user is currently viewing a specified URL, and useLinkProps()
to get a href
and onClick
that’s hooked into the browser history.
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom'
import { Router, View, useActive, useLinkProps } from 'react-navi'
import Layout from './layout'
import { List, ListItem } from './list'
import routes from './routes'
function ListItemLink({ children, href, ...rest }) {
let active = useActive(href)
let linkProps = useLinkProps({ href })
return (
<ListItem
as="a"
active={active}
children={children}
{...rest}
{...linkProps}
/>
)
}
ReactDOM.render(
<Router routes={routes}>
<Layout
left={
<List>
<ListItemLink
href="/hats"
title="Hats"
description="Don't get burned"
/>
<ListItemLink
href="/other"
title="Other"
description="Not-a-flamethrowers, etc."
/>
</List>
}
right={
<Suspense fallback={null}>
<View />
</Suspense>
}
/>
</Router>,
document.getElementById('root')
)