TrackedNavigationContext
HOC wrapping the given Component
in a NavigationContext and enriching it with the objectiv
prop.
TrackedNavigationContext: <T>(props: T & {
objectiv: {
Component: ElementType | keyof ReactHTML,
id: string,
normalizeId?: boolean
}
}) => JSX.Element
objectiv
prop attributes
type | default value | ||
---|---|---|---|
required | Component | ElementType | keyof ReactHTML | |
required | id | string | |
optional | normalizeId | boolean | true |
Returns
JSX.Element
Automatic Events
None.
Usage example
Elements
import { TrackedNavigationContext } from '@objectiv/tracker-react';
<TrackedNavigationContext<ComponentProps<'nav'>>
objectiv={{
Component: 'nav',
id: 'top-nav'
}}
>
<a href={'/'}>Homepage</a>
<a href={'/privacy'}>Privacy</a>
<a href={'/contact'}>Contact</a>
</TrackedNavigationContext>
ID normalization
By default, all Tracked Context Components automatically normalize their Context identifiers to a kebab-cased format.
This can be disabled via the normalizeId
option. This is useful when identifiers need to be preserved for cross-platform
concerns or if they are standardized identifiers, e.g. a code from a backend API.
In this example the identifier, which would normally be top-navigation
, will be preserved as Top Navigation
:
import { TrackedNavigationContext } from '@objectiv/tracker-react';
<TrackedNavigationContext<ComponentProps<'nav'>>
objectiv={{
Component: 'nav',
id: 'Top Navigation',
normalizeId: false
}}
>
...
</TrackedNavigationContext>
Components
The Component
prop doesn't need to be a JSX Element. Actually, more often than not, it will probably be another Component.
Here is an example of how to wrap around a hypothetical NavBar component.
import { NavBar, NavBarProps } from '../components';
import React, { ComponentProps } from 'react';
import { TrackedNavigationContext } from '@objectiv/tracker-react';
export type TrackedNavBarProps = NavBarProps & {
objectiv?: Omit<TrackedContextObjectivProp, 'Component'>;
};
export const TrackedNavBar = React.forwardRef<HTMLDivElement, TrackedNavBarProps>(
({ objectiv, ...nativeProps }, ref) => (
<TrackedNavigationContext<ComponentProps<'nav'>>
{...nativeProps}
ref={ref}
objectiv={{
...objectiv,
Component: NavBar,
id: objectiv?.id ?? 'navbar'
}}
/>
)
);
This can now be used like this:
<TrackedNavBar>
<MenuItem>Menu 1</MenuItem>
<MenuItem>Menu 2</MenuItem>
<MenuItem>Menu 3</MenuItem>
</TrackedNavBar>
<TrackedNavBar objectiv={{ id: 'top-nav' }}>
<MenuItem>Menu 1</MenuItem>
<MenuItem>Menu 2</MenuItem>
<MenuItem>Menu 3</MenuItem>
</TrackedNavBar>
<TrackedNavBar id={'top-nav'}>
<MenuItem>Menu 1</MenuItem>
<MenuItem>Menu 2</MenuItem>
<MenuItem>Menu 3</MenuItem>
</TrackedNavBar>
Check these how-to guides for more thorough examples:
TrackedNavigationContext
internally uses NavigationContextWrapper.