Search code examples
reactjsreact-routermaterial-uibottomnavigationview

No impact on URL with Material-UI BottomNavigation


I am trying to create a Bottom Navigation bar using material-ui (link:https://material-ui.com/components/bottom-navigation/).

Unfortunately, when I created the component, clicking on each tap did not affect my URL.

Initially, I was using the Link component from React, which allowed me to route between various components. However, as I integrate the Link component into the BottomNavigation component, the style changes and is not working properly anymore.

Here's my current code (without the Link component):

function NavigationAuth() {
  const [value, setValue] = React.useState("/");

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <BottomNavigation
      value={value} 
      onChange={handleChange} 
      showLabels
    >
      <BottomNavigationAction label="Home" value="/" icon={<HomeIcon />} />
      <BottomNavigationAction label="Progress" value="/home" icon={<TimelineIcon />} />
      <BottomNavigationAction label="Vote" value="/overview" icon={<ThumbsUpDownIcon />} />
      <BottomNavigationAction label="Account" value="/account" icon={<AccountCircleIcon />} />
    </BottomNavigation>
  );
}

Does anyone have an idea how I can actually change the URL (while using the BottomNavigation component) as a normal Link component would do?

Many thanks in advance!


Solution

  • You can import {useHistory} from react-router-dom and use it to change the URL:

    function NavigationAuth() {
        const [value, setValue] = React.useState("");
        const history = useHistory();
    
        const handleChange = (event, newValue) => {
          history.push(`/${newValue}`);
          setValue(newValue);
        };
    
        return (
          <BottomNavigation
            value={value} 
            onChange={handleChange} 
            showLabels
          >
            <BottomNavigationAction label="Home" value="" icon={<HomeIcon />} />
            <BottomNavigationAction label="Progress" value="progress" icon={<TimelineIcon />} />
            <BottomNavigationAction label="Vote" value="overview" icon={<ThumbsUpDownIcon />} />
            <BottomNavigationAction label="Account" value="account" icon={<AccountCircleIcon />} />
          </BottomNavigation>
        );
      }