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 :-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With