Skip to content
+

Rich Tree View - Focus

Learn how to focus Tree View items.

Imperative API

To use the apiRef object, you need to initialize it using the useRichTreeViewApiRef() or useRichTreeViewProApiRef() hook as follows:

// Community package
const apiRef = useRichTreeViewApiRef();

return <RichTreeView apiRef={apiRef} items={ITEMS} />;

// Pro package
const apiRef = useRichTreeViewProApiRef();

return <RichTreeViewPro apiRef={apiRef} items={ITEMS} />;

When your component first renders, apiRef.current is undefined. After the initial render, apiRef holds methods to interact imperatively with RichTreeView.

Focus a specific item

Use the focusItem() API method to focus a specific item.

apiRef.current.focusItem(
  // The DOM event that triggers the change
  event,
  // The id of the item to focus
  itemId,
);
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { RichTreeView } from '@mui/x-tree-view/RichTreeView';
import { useRichTreeViewApiRef } from '@mui/x-tree-view/hooks';
import { MUI_X_PRODUCTS } from './products';

export default function ApiMethodFocusItem() {
  const apiRef = useRichTreeViewApiRef();
  const handleButtonClick = (event: React.SyntheticEvent) => {
    apiRef.current?.focusItem(event, 'pickers');
  };

  return (
    <Stack spacing={2}>
      <div>
        <Button onClick={handleButtonClick}>Focus pickers item</Button>
      </div>
      <Box sx={{ minHeight: 352, minWidth: 250 }}>
        <RichTreeView items={MUI_X_PRODUCTS} apiRef={apiRef} />
      </Box>
    </Stack>
  );
}

API

See the documentation below for a complete reference to all of the props and classes available to the components mentioned here.