I would like to add checkboxes inside Antd Submenu. Following is my code.
<Menu style = {{height: '100vh', overflow: 'auto'}} mode="inline" inlineCollapsed = "false">
<SubMenu key="sub1" onTitleClick = {subMenuTitleClick} title={<span><Icon type="mail" onClick = {this.temp}/><Checkbox onClick = {this.checkboxClick}></Checkbox><span>Sources</span></span>}>
<Menu.Item key={key1}>{detail.docTtl}</Menu.Item>
</SubMenu>
</Menu>
Here, click on Submenu should call subMenuTitleClick and click on checkbox should call checkboxClick.
Ok, so I don't have the full scope but I'll try some assumptions :
Do not use whitespeces in properties declarations :
onClick={} : good. onClick = {} : bad
onTitleClick={subMenuTitleClick} is not a click event, so make sure the <SubMenu/> component handles it correctly
Your <Checkbox/> has a onClick={this.temp}: make sure that this.temp is actually a click handler function
Here is an example. I removed a few things to make the whole more readable
class MyClass extends React.Component {
handleWhateverClic = () => { /* Do stuff */ }
handleCheckboxClick = () => { /* Do stuff */ }
render() {
return (
<Menu >
<SubMenu onTitleClick={this.handleWhateverClic} title={
<span>
<Icon type="mail" onClick={this.handleWhateverClic}/>
<Checkbox onClick={this.handleCheckboxClick} />
<span>Sources</span>
</span>
}>
<Menu.Item>{detail.docTtl}</Menu.Item>
</SubMenu>
</Menu>
)
}
}
Related
I have a dropdown menu builth with Headless UI Menu component, but the menu links inside this dropdown are not getting focused on keyboard navigation.
my code goes something like so:
function Dropdown(parent, children) {
return (
<Menu as="div" className="Submenu">
{
({close}) => (
<>
<Menu.Button>
{ parent.label }
</Menu.Button>
<Menu.Items as="ul" className="subitems">
{
children.map(child => (
<Menu.Item as="li" className="subitem" key={ child.id }>
<Link href={ child.link }>
{ child.label }
</Link>
</Menu.Item>
))
}
</Menu.Items>
</>
)
}
</Menu>
);
}
The only thing getting the focus is the <ul></ul that wraps the items, but once I press tab the dropdown closes and the focus goes to the next item on the parent level menu.
The final html rendered is this:
I've tried to add tabIndex={0} to the tags, but the output stays the same.
I also tried to create a Link wrapper component ike suggested here, but it didn't work.
I need to add a Context Menu to my TreeWiew. I managed to do this with this mui.com's Menu but I don't know how to get the selected item in the tree where the user did the right click to open the context menu. For example, let's say the user open the context menu and click on "Copy message" i'd like to know which node the user selected (Calendar, OSS, index.js etc) and do the proper action. I've tried looking in the TreeView's thing like onNodeSelect but it doesn't fire when you open the context menu over the item.
Currently the code look like this:
export default function FileSystemNavigator() {
const [contextMenu, setContextMenu] = React.useState<{
mouseX: number;
mouseY: number;
} | null>(null);
const handleContextMenu = (event: React.MouseEvent) => {
event.preventDefault();
setContextMenu(
contextMenu === null
? {
mouseX: event.clientX + 2,
mouseY: event.clientY - 6
}
: // repeated contextmenu when it is already open closes it with Chrome 84 on Ubuntu
// Other native context menus might behave different.
// With this behavior we prevent contextmenu from the backdrop to re-locale existing context menus.
null
);
};
const handleClose = () => {
setContextMenu(null);
};
return (
<div onContextMenu={handleContextMenu} style={{ cursor: "context-menu" }}>
<TreeView
aria-label="file system navigator"
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
sx={{ height: 240, flexGrow: 1, maxWidth: 400, overflowY: "auto" }}
>
<TreeItem nodeId="1" label="Applications">
<TreeItem nodeId="2" label="Calendar" />
</TreeItem>
<TreeItem nodeId="5" label="Documents">
<TreeItem nodeId="10" label="OSS" />
<TreeItem nodeId="6" label="MUI">
<TreeItem nodeId="8" label="index.js" />
</TreeItem>
</TreeItem>
</TreeView>
<Menu
open={contextMenu !== null}
onClose={handleClose}
anchorReference="anchorPosition"
anchorPosition={
contextMenu !== null
? { top: contextMenu.mouseY, left: contextMenu.mouseX }
: undefined
}
>
<MenuItem onClick={handleClose}>Copy Ctrl+C</MenuItem>
<MenuItem onClick={handleClose}>Delete</MenuItem>
<MenuItem onClick={handleClose}>Move</MenuItem>
<MenuItem onClick={handleClose}>Email</MenuItem>
</Menu>
</div>
);
}
Here's a live code example
You can achieve this by a small hack - trigger the click event on opening the context menu. That will fire an onNodeSelect callback of the TreeView component.
export default function FileSystemNavigator() {
// ...
const [selectedNodeId, setSelectedNodeId] = React.useState<string | null>(
null
);
const handleContextMenu = (event: React.MouseEvent) => {
event.target.click();
event.preventDefault();
// ...
};
const handleNodeSelect = (event, nodeId) => {
setSelectedNodeId(nodeId);
};
return (
<div onContextMenu={handleContextMenu} style={{ cursor: "context-menu" }}>
<TreeView
{/* ... */}
onNodeSelect={handleNodeSelect}
></TreeView>
<Menu>
{/* ... */}
<MenuItem onClick={handleClose}>Delete node {selectedNodeId}</MenuItem>
{/* ... */}
</Menu>
</div>
);
}
It will produce the following outcome:
Since you have only one context menu that have dynamically calculated position based on where right click happened, then you should use event from onContextMenu handler in order to find tree item that was right-clicked.
For example, when you right click on 'Application' node, inside event.target of your handleContextMenu you will find <div class="MuiTreeItem-label">Applications</div> - and you just need to store this piece of information in inner state, and then reuse that same piece of state inside MenuItem click handlers. I assume you can attach some custom attributes, or maybe id to TreeItem, so you can additionally simplify resolver of clicked tree item(to avoid inspecting innerText of HTML div).
I have antd Menu inside collapsible Sider. I've set default open keys for one of Submenus and they should open one at a time. Here is my code for the Menu:
const MainMenu = ({ defaultOpenKeys }) => {
const [openKeys, setOpenKeys] = useState(defaultOpenKeys);
const rootKeys = ["sub1", "sub2"];
// Open only one submenu at a time
const onOpenChange = props => {
const latestOpenKey = props.find(key => openKeys.indexOf(key) === -1);
if (rootKeys.indexOf(latestOpenKey) === -1) {
setOpenKeys(props);
} else {
setOpenKeys(latestOpenKey ? [latestOpenKey] : defaultOpenKeys);
}
};
return (
<Menu
theme="dark"
openKeys={openKeys}
defaultSelectedKeys={["1"]}
mode="inline"
onOpenChange={onOpenChange}
>
<Menu.Item key="1">
Option 1
</Menu.Item>
<SubMenu key="sub1" title="User">
<Menu.Item key="2">Tom</Menu.Item>
</SubMenu>
<SubMenu key="sub2" title="Team">
<Menu.Item key="3">Team 1</Menu.Item>
</SubMenu>
</Menu>
);
};
export default MainMenu;
I pass defaultOpenKeys from the Sider.
const SiderDemo = () => {
const [collapsed, setCollapsed] = useState(false);
const toggleSider = () => {
setCollapsed(!collapsed);
};
return (
<Layout style={{ minHeight: "100vh" }}>
<Button type="primary" onClick={toggleSider}>
{React.createElement(
collapsed ? MenuFoldOutlined : MenuUnfoldOutlined
)}
</Button>
<Sider
collapsible
collapsed={collapsed}
collapsedWidth={0}
trigger={null}
>
<Menu defaultOpenKeys={["sub1"]} />
</Sider>
...
</Layout>
);
};
It works on mount, but when I collapse the Sider, defaultOpenKeys are being reset. How can I keep defaultOpenKeys from being reset, when the Sider is collapsed?
I have created a codesandbox and added console log in the Menu. You can see that defaultOpenKeys and openKeys are the same on mount. When I collapse the Sider, the console log is triggered twice. The first time defaultOpenKeys and openKeys are the same. And the second time openKeys become empty. How can I fix that?
Reason: on closing the sidebar it is closing opened sidemenu so it gonna trigger openchange with empty array and hence your logic making it reset to empty.
Here is code sandbox link with updated code
https://codesandbox.io/s/sider-demo-0der5?file=/Menu.jsx
Suggestion: Its anti pattern to assign props to initial state. if prop value changed in parent component then the new prop value will never be displayed because intial state will never update the current state of the component. The initialization of state from props only runs when the component is first created
I use antd 3.15 and GraphQL to fetch data and generate a list of SubMenu and Menu.Item inside of Menu. However, I got the error message like this Uncaught TypeError: Cannot read property 'isRootMenu' of undefined I have no idea what is wrong with my code. isRootMenu is not a prop listed anywhere on the doc. ant.design/components/menu/#header and when I hardcoded all the SubMenu and Menu.List there is no problem. Can I iterate data from GraphQL to generate the SubMenu and Menu.List?
Can someone help me with this issue, please? Thank you! Here is my code:
import * as React from 'react';
import './SideNav.scss';
import { Menu, Icon } from 'antd';
import gql from 'graphql-tag';
import { Query } from 'react-apollo';
const FLOORS_QUERY = gql`
query {
getAllFloors {
id
floorName
rooms {
id
roomName
roomNumber
roomDescription
}
}
}
`;
export default class SideNav extends React.Component {
render() {
return (
<Menu theme="light" defaultSelectedKeys={['1']} mode="inline">
<Query query={FLOORS_QUERY}>
{({ loading, error, data }) => {
if (loading) return <h4> loading... </h4>;
if (error) console.log(error);
console.log(data);
return (
<React.Fragment>
{data.getAllFloors.map((floor) => (
<SubMenu
key={floor.id}
title={
<span>
<Icon type="plus" />
<span>{floor.floorName}</span>
</span>
}
>
<React.Fragment>
{floor.rooms.map((room) => (
<Menu.Item key={room.id}>{room.roomNumber}</Menu.Item>
))}
</React.Fragment>
</SubMenu>
))}
</React.Fragment>
);
}}
</Query>
</Menu>
);
}
}
You should pass the props to the submenu.
const CustomComponent = (props) => (
<Menu.SubMenu title='SubMenu' {...props}>
<Menu.Item>SubMenuItem</Menu.Item>
</Menu.SubMenu>
)
so a solution to your question would be to do the following;
move the query outside of the containing menu
pass the props to the SubMenu
const FloorMapSubMenu = ({ id, floorName, rooms, ...other }) => {
return (
<Menu.SubMenu
key={id}
title={
<span>
<Icon type="plus" />
<span>{floorName}</span>
</span>
}
{...other} // notice the other props, this is were the 'isRootMenu' is injected from the <Menu> children
>
<React.Fragment>
{rooms.map((room) => (
<Menu.Item key={room.id}>{room.roomNumber}</Menu.Item>
))}
</React.Fragment>
</Menu.SubMenu>
)
}
class SideNav extends React.Component {
render() {
return (
<Query query={FLOORS_QUERY}>
{({ loading, error, data }) => {
if (loading) return <h4> loading... </h4>
if (error) console.log(error)
console.log(data)
return (
<Menu theme='light' defaultSelectedKeys={['1']} mode='inline'>
{data.getAllFloors.map((floor, i) => (
<FloorMapSubMenu key={i} id={floor.id} floorName={floor.floorName} rooms={floor.rooms} />
))}
</Menu>
)
}}
</Query>
)
}
}
I found out the Ant design SubMenu needs to use the parent to check some properties like isRootMenu at
SubMenu.js:260
getPopupContainer = props.parentMenu.isRootMenu ? props.parentMenu.props.getPopupContainer : function (triggerNode) {
return triggerNode.parentNode;
}
In order to solve it you need to manually pass parent props into SubMenu like
<Menu.SubMenu {...this.props}/>
to solve the problem. Hope this helps u
Related Github issue item https://github.com/react-component/menu/issues/255
I had this issue while trying to add a <div> as a child of Menu. I just added an empty Menu.Item as the first child of my menu, and the error went away.
<Menu>
<Menu.Item style={{display: 'none'}} />
<div>...</div>
</Menu>
I ran into the same issue. It seems Antd does not allow to place arbitrary components into a Menu/SubMenu. My guess is that Menu.Item needs to get some props, which are passed from Menu/SubMenu to its children.
So you can either create a custom component that passes all props down, or remove the inner <React.Fragment> declaration (the one that is inside the SubMenu), which is not needed anyway.
I was able to make it work by putting the <Query> Component at the top:
<Query query={FLOORS_QUERY}>
{({ loading, error, data }) => {
if (loading) return <Spin />;
if (error) console.log(error);
console.log(data);
return (
<Menu theme="light" defaultSelectedKeys={['1']} mode="inline">
{data.getAllFloors.map((floor) => (
<SubMenu
key={floor.id}
title={
<Link to="/{floor.id}">
<span>
<Icon type="plus" />
<span>{floor.floorName}</span>
</span>
</Link>
}
>
{floor.rooms.map((room) => (
<Menu.Item key={room.id} onClick={this.showRoomProfile}>
{room.roomNumber}
</Menu.Item>
))}
</SubMenu>
))}
</Menu>
);
}}
</Query>
According to the Typescript definitions the childrens of Menu should be of kind Item, SubMenu, ItemGroup or Divider. If you must place a different component on the Header, wrap the Menu and the desired component on a Header component component as such:
import { Layout } from 'antd';
const { Header, Footer, Sider, Content } = Layout;
<Layout>
<Layout.Header>
<div className="logo" />
<Menu>
<Menu.Item key="1">nav 1</Menu.Item>
<Menu.Item key="2">nav 2</Menu.Item>
</Menu>
<Layout.Header>
</Layout>
I have run into the same issue. But my issues was I have using ternary condition to show some menu's dynamically inside part used the <></> element. That caused me this issue. Once removed that everything work fine.
I create a menu with React.js. But there is a problem for me. There is 2 sub menus and these sub menus have their menu items. When I hover one of them it shows its menu items. But when I click another sub menu, it still shows previous menu items. How can I prevent it ? My code:
My first class : Sider.js
function Sider(props) {
return (
<Menu mode="horizontal">
selectedKeys={[props.current]}
onClick={props.handleClick}
<SubMenu title={<span><Icon type="setting" />Sub menu 1</span>}>
<MenuItem> menu item 1</MenuItem>
<MenuItem> menu item 2</MenuItem>
</SubMenu>
<SubMenu title={<span><Icon type="laptop" />Sub menu 2</span>}>
<MenuItem> menu item 3</MenuItem>
</SubMenu>
</Menu>
);
}
This is my main class which I call Sider function.
Main.js :
import PropTypes from 'prop-types';
class Main extends React.Component {
constructor(props) {
super(props)
this.state = {
current: 'MenuItem'
}
}
handleClick = (e) => {
this.setState({
current: e.key,
});
}
render() {
return (
<div>
<Sider navigation={this.props.navigation} handleClick={this.props.handleClick} current={this.state.current />
</div>
);
}
}
Main.propTypes = {
handleClick: PropTypes.func,
};
You can use key to maintain active state of selected sub menu and use selectedKeys. see the working code below
I have made working menu in codeopen here codepen
import PropTypes from 'prop-types';
class App extends React.Component {
state = {
current: 'menu1:1',
}
handleClick = (e) => {
this.setState({
current: e.key,
});
}
render() {
return (
<div>
<Sider navigation={this.props.navigation} handleClick={this.handeClick} current={this.state.current} />
</div>
);
}
}
App.propTypes = {
handleClick: PropTypes.func,
};
And your Sider function will be like below
function Sider(props) {
return (
<Menu onClick={props.handleClick} selectedKeys={[props.current]}>
<SubMenu title={<span><Icon type="setting" />Sub menu 1</span>}>
<MenuItem key="setting:1"> menu item 1</MenuItem>
<MenuItem key="setting:2"> menu item 2</MenuItem>
</SubMenu>
<SubMenu title={<span><Icon type="laptop" />Sub menu 2</span>}>
<MenuItem key="laptop:1"> menu item 3</MenuItem>
</SubMenu>
</Menu>
);
}
For documentations please read horizontal menu and Vertical Menu
How did you implement the hovering mechanism? Please add more code.
Do you change the inner state of each SubMenu when you hover out?
You should better read the documentation for antd's components.
Go to the following link to better understand how to use these components.