Search code examples
reactjsreact-hooksreact-link

Put Link in StyledMenuItem in React


I wanted to put Link so i can navigate to other pages in react. Why is this not navigating

CODE

  <StyledMenu
  anchorEl={settingsMenu}
  keepMounted
  open={Boolean(settingsMenu)}
  onClose={handleClose}>

  <StyledMenuItem>
    <ListItemIcon component={Link} to={`/accounts`}>
      <PersonIcon />
    </ListItemIcon>
    <ListItemText primary="accounts" />
  </StyledMenuItem>
  <StyledMenuItem component={Link} to={`/orders`}>
    <ListItemIcon>
      <OrderIcon />
    </ListItemIcon>
    <ListItemText primary="Orders" />
  </StyledMenuItem>
</StyledMenu>;

Solution

  • Assuming <StyledMenuItem> is your custom component, you can easily do this by wrapping the entire JSX in the component prop. For the other props passed to it (e.g., to), simply destructure them and place them as props to the new wrapper component.

    import React, { Component } from "react";
    export default class StyledMenuItem extends Component {
        render() {
    
            // simply checks to see if a component prop is passed
            let WrapperComponent = this.props.component;
            if (WrapperComponent === undefined) {
                WrapperComponent = React.Fragment;
            }
    
            return (
                <WrapperComponent {...this.props}>
                    {this.props.children}
                </WrapperComponent>
            );
        }
    }
    

    This somehow imitates the behaviour of Material UI MenuItem like I previously had written about on my comment.