I've been working around building a notion-clone and I'm stuck on the feature where if you click "/" then a menu appears which gives out options to change the current block to the preferred one which user selects I'm able to change the block via the menu but I have to use mouse to select an option
const allowedTags = [
{
label: "h1",
value: "heading-one",
},
{
label: "h2",
value: "heading-tw0",
},
{
label: "quote",
value: "block-quote",
},
{
label: "numbered",
value: "numbered-list",
},
{
label: "bullets",
value: "bulleted-list",
},
{
label: "p",
value: "paragraph",
},
];
const renderMenu = () => {
return (
<div className="editor__menu" style={coordinates}>
{allowedTags.map((item, key) => {
return (
<p
className="editor__menu--item"
key={key}
onClick={() => {
CustomEditor.toggleBlock(editor, item.value);
setMenu(false);
}}
>
{item.label}
</p>
);
})}
</div>
);
};
Here I'm mapping through the allowed tags and creating a list In the editor, if someone types "/" then this menu should come up which is handled by onKeyDown()
onKeyDown={(event) => {
if (event.key === "/") {
openMenu();
}
}
Everything works completely fine! But the only thing I'm stuck on is I'm not able to focus on the menu and control it via keyboard keys, can anyone help around this?
I advise you to use button tag instead p, h1 or h2. But if there is no other way you can use "tabindex" attribute, like this:
<h1 tabindex="0">Hello</h1>
<p tabindex="0">World</p>
And add this to your function
openMenu();
const element = document.getElementsByClassName('editor__menu--item')[0]
element.focus();
It let focusing on element from keyboard. In addition you can use tabindex="-1" on button if you want to disable focus.