1

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>;
Joseph
  • 7,042
  • 23
  • 83
  • 181
  • what do you mean by this is not navigating? the route is not changing? have you setup your client-side routing correctly? add more code/context to your question – 95faf8e76605e973 Jul 21 '20 at 05:42
  • @95faf8e76605e973. Is putting `component={Link} to={`/orders`}` in `StyledMenuItem` okay? Maybe its not acceptable – Joseph Jul 21 '20 at 05:45
  • Perhaps. the component prop implementation looks similar to what [Material UI MenuItem](https://material-ui.com/api/menu-item/) has. Is this what you intended to do? is StyledMenuItem your custom component? if so just append `this.props.component` to the JSX – 95faf8e76605e973 Jul 21 '20 at 05:49
  • @95faf8e76605e973. How would i do it? Could you answer it? Thanks – Joseph Jul 21 '20 at 06:11

1 Answers1

1

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.

95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
  • I'm sorry but my problem is when i click the StyleMenuItem it would redirect me to a certain route. Pls check my edited question – Joseph Jul 21 '20 at 06:44
  • Are you using react-router? Check if you've imported correct libraries, Example: `import { Link } from 'react-router-dom';` – 95faf8e76605e973 Jul 21 '20 at 06:48