Material-components-web-components: mwc-list-item not working as anchor / link element

Created on 9 Apr 2020  路  6Comments  路  Source: material-components/material-components-web-components

Describe the bug
It's unclear how to use list items as links.

As described here none of the strategies work. Just pointing out in case this specific instance wasn't known.

To Reproduce
Steps to reproduce the behavior:

  1. Try to use a mwc-list-item as a link / anchor

Expected behavior
More compose-ability of these components. Probably that mwc-list-item can take an href attribute.

Screenshots
https://codesandbox.io/s/hungry-sun-5mtcm?file=/App.svelte

Browser Version (please complete the following information):

  • OS: Manjaro Linux
  • Browser: Brave
  • Version: 1.7.72 Chromium: 80.0.3987.149

Additional context
@material/[email protected]

List Components Low Bug Enable new use cases improve ergonomics

All 6 comments

Hello, for now you should simply be able to wrap a list-item in an anchor tag. e.g.

<mwc-list>
  <a href="google.com"><mwc-list-item>google</mwc-list-item></a>
  <a href="bing.com"><mwc-list-item>bing</mwc-list-item></a>
  <a href="duckduckgo.com"><mwc-list-item>duck duck go</mwc-list-item></a>
</mwc-list>

Keeping issue open as this is still an open question on how to do this systematically.

Alternatively, you can subclass ListItemBase from @material/mwc-list/list-item-base and add your own properties or wrap the shadow root contents in an anchor yourself.

Check my codesandbox "outer" example. Link text is underlined (not sure if that's the only styling error). I'll try the subclass way or just use the core material-components-web library for now, thanks.

Heya, you can simply set text-decoration: none on the wrapping <a>

Hello, for now you should simply be able to wrap a list-item in an anchor tag.

When I do this, I lose the ability to use keyboard navigation in the list. Any workarounds there?

Alternatively, you can subclass ListItemBase from @material/mwc-list/list-item-base and add your own properties or wrap the shadow root contents in an anchor yourself.

Do you know if this would have the same issue with keyboard nav?

Hello, unfortunately you cannot wrap with an anchor tag right now and keep selection + keyboard nav (choice made for performance reasons, possible reconsideration to happen in future). Subclassing is the way to go. The issue causing the keyboard nav is that list currently only looks at direct children to check if they are list items. Wrapping it, the list can no longer index it. Subclassing will keep it as the direct child of list and thus work

Thank you for fast reply :)

Did a quick prototype locally and it seems to be working! I'm extending ListItem though as I want to be able to override styles. I'm assuming that's fine since ListItem appears to be just a styled ListItemBase.

Was this page helpful?
0 / 5 - 0 ratings