Ant Design - Deselect/Remove active status from Menu.Item programmatically

Viewed 3072

Following situation:

A top menu with {LOGO - AntMenu [Horizontal] - Other stuff}.

The logo redirects to the HomePage, while each Menu.Item redirects to another page of the app.

Current behavior: If I click on one of the Menu.Item, the relative route gets properly activated (I use a react-router Link) AND the "Active" effect gets applied to the related Menu.Item.

However, if after that I click the LOGO then the "Active" effect remains on the previously selected Item and I cannot find a way to programmatically remove it without hacking the menu.

I've tried setting the Menu.selectedKeys array to null or something else, but it breaks and can't see any other property on the doc that can help.

Any Idea?

3 Answers

Provide path to selected keys prop in an array. To get path if you are using react router V5 you can use hooks or use withRouter for earlier versions.

Now only the matched pathname in URL will be active(highlighted) in side menu, if it didn't then it wont be active.

const location = useLocation();
const { pathname } = location;




<Menu mode="inline" theme={theme} selectedKeys={[pathname]}>
      <Menu.Item key="/home">
        <Link to="/home">
          <span>Home</span>
        </Link>
      </Menu.Item>
      <Menu.Item key="/songs">
        <Link to="/songs">
          <span>Songs</span>
        </Link>
      </Menu.Item>
<Menu>

It would be good to post some code from your project.

I used react redux and react-router-dom, so maybe you will have different code but hope it will be helpful for you.

export const Path = {
root: '/',  
books: '/books',
authors: '/authors'
}

...
<Router>
    <div>
      <ul>
        <li><Link to='/'>   
                <div> 
                   <img src={your logo} />
                </div>
             </Link>
        </li>      
        <li><Link to='/books'>Books</Link></li>
        <li><Link to='/authors'>Authors</Link></li>
      </ul>
      <main>
        <Route exact path={Path.root}/>
        <Route path={Path.books} component={BooksTableContainer}/> 
        <Route path={Path.authors} component={AuthorTableContainer}/>            
      </main>
    </div>
  </Router>

Antd Menu takes selectedKeys as argument. You just need to add state const [selectedKeys, setselectedKeys] = useState<Array<string>>([]); and when you click on Menu.Item - set it's key to state setselectedKeys([e.key]);. And when you press LOGO - setselectedKeys([]);

Related