Is it possible to use material-ui button navigation with react-router?
Yes, it's possible. You need to use the component
prop:
import { Link } from 'react-router-dom';
import BottomNavigation from '@material-ui/core/BottomNavigation';
import BottomNavigationAction from '@material-ui/core/BottomNavigationAction';
// ....
<BottomNavigation value={value} onChange={this.handleChange}>
<BottomNavigationAction
component={Link}
to="/signal"
label="signal"
value="signal"
icon={<ShowChart />}
className={classes.content}
/>
</BottomNavigation>
(the to
prop is for React Router's Link
component)
This works with any Material-UI component that inherits from ButtonBase
.
https://material-ui.com/api/bottom-navigation-action/
Inheritance
The properties of the ButtonBase component are also available. You can take advantage of this behavior to target nested components.
https://material-ui.com/api/button-base/
Props
component
- The component used for the root node. Either a string to use a DOM element or a component.
Just to add on to the great answer by @thirtydot , in case the user types into the search and visits a particular webpage directly (other than default) e.g. "www.yoursite.com/tab2", instead of clicking the 2nd button, this may cause a mismatch between the site that is showing and the BottomNav Button that is focused (usually the 1st button).
Here is what I did:
I used window.location.pathname
to get the current path which is '/tab2' directly.
Here is my code for my particular use case....
function BottomNavBar(){
const pathname = window.location.pathname; // in case user visits the path directly. The BottomNavBar is able to follow suit.
const [value, setValue] = React.useState(pathname);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<BottomNavigation value={value} onChange={handleChange} showLabels={true} >
<BottomNavigationAction label="home" value="/" icon={<HomeIcon />} component={Link} to='/'/>
<BottomNavigationAction label="resources" value="/resources" icon={<ResourcesIcon /> } component={Link} to='/resources'/>
<BottomNavigationAction label="Q&A" value="/qna" icon={<QnAIcon />} component={Link} to='/qna'/>
<BottomNavigationAction label="profile" value="/profile" icon={<ProfileIcon />} component={Link} to='/profile'/>
</BottomNavigation>
);
}