Reputation: 5914
This is the ListItem component I'm using:
<ListItem
activeClassName={classes.activeListItem}
className={classes.listItem}
component={NavLink}
to="/dashboard"
>
<ListItemIcon className={classes.listItemIcon}>
<DashboardIcon />
</ListItemIcon>
<ListItemText
classes={{ primary: classes.listItemText }}
primary="Dashboard"
/>
</ListItem>
This raises the error below:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `ForwardRef(ListItem)`.
in NavLink (created by ForwardRef(ListItem))
in ForwardRef(ListItem) (created by WithStyles(ForwardRef(ListItem)))
in WithStyles(ForwardRef(ListItem)) (at sidebar/index.tsx:72)
in div (created by ForwardRef(List))
in ForwardRef(List) (created by WithStyles(ForwardRef(List)))
in WithStyles(ForwardRef(List)) (at sidebar/index.tsx:71)
in nav (at sidebar/index.tsx:44)
in Sidebar (created by WithStyles(Sidebar))
in WithStyles(Sidebar) (at dashboard/index.tsx:45)
in div (created by ForwardRef(Paper))
in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
in WithStyles(ForwardRef(Paper)) (created by ForwardRef(Drawer))
in div (created by ForwardRef(Drawer))
in ForwardRef(Drawer) (created by WithStyles(ForwardRef(Drawer)))
in WithStyles(ForwardRef(Drawer)) (at dashboard/index.tsx:37)
in div (at dashboard/index.tsx:30)
in Dashboard (created by WithStyles(Dashboard))
in WithStyles(Dashboard) (created by Context.Consumer)
in Route (at Routes.tsx:16)
in Switch (at Routes.tsx:10)
in Routes (at App.tsx:15)
in Router (at App.tsx:14)
in ThemeProvider (at App.tsx:13)
in App (at src/index.tsx:7)
When I use the ListItem without a NavLink, everything works fine:
<ListItem button key={text}>
<ListItemIcon><InboxIcon /></ListItemIcon>
<ListItemText primary={text} />
</ListItem>
So I guess there's something wrong in the usage of component
property of the ListItem but I can't find out why with my current level of knowledge :-)
Upvotes: 5
Views: 4150
Reputation: 81086
ListItem
tries to specify a ref on the component you specify via the component
prop.
Refs are not supported by function components except by wrapping them using React's forwardRef.
React Router's NavLink is a function component and currently it is not wrapped by React.forwardRef
.
The documentation here explains how to wrap react-router's Link
(and NavLink
just wraps Link
so the same solution will work) so that it supports receiving a ref.
Upvotes: 3
Reputation: 1185
The ButtonBase component provides a property to handle this use case: component. This is achieved by attaching a ref to the component and expecting that the component forwards this ref to the underlying DOM node.
Follow this link: https://material-ui.com/components/buttons/#third-party-routing-library
Upvotes: 0