We explore all kinds of technologies, starting from programming, electronics ending in the photography sector. A bit for everyone.

Thursday, March 26, 2020

MemoryRouter and Material UI Navigation

Are you wondering why your MemoryRouter and Navigation from Material UI don't properly work?



Maybe your <BottomNavigation> gets messed up when it's wrapped by a <Link> from react-router-dom?

It took me one day to sort this out. The official documentation of the Bottom Navigation (Action) from MUI is non-existent.

First, you must know that the MemoryRouter is rarely used, because of the server's inability to redirect you to a specific URL. (The URLs are all stored in memory)

However, when you want to use it, here's how to do the Links properly.

return (
    <MemoryRouter>
        <ThemeProvider theme={theme}>
            <Switch>
                <Route exact path="/">
                    <SubjectSelector />
                </Route>
                <Route path="/score">
                    <Scoreboard />
                </Route>
                <Route path="/contribute">
                    <Contribute />
                </Route>
            </Switch>

            <div class="navbar-container">
                <BottomNavigation
                    value={this.state.currentPage}
                    onChange={(event, newValue) => {
                        this.setState({ currentPage: newValue });
                    }}
                    showLabels
                >
                    <BottomNavigationAction
                        component={Link}
                        label="Choose"
                        icon={<SchoolIcon />}
                        to="/"
                    />
                    <BottomNavigationAction
                        component={Link}
                        label="Play"
                        icon={<PlayArrowIcon />}
                        to="/play"
                    />
                    <BottomNavigationAction
                        component={Link}
                        label="Statistics"
                        icon={<BarChartIcon />}
                        to="/score"
                    />
                    <BottomNavigationAction
                        component={Link}
                        label="Contribute"
                        icon={<AddIcon />}
                        to="/contribute"
                    />
                </BottomNavigation>
            </div>
        </ThemeProvider>
    </MemoryRouter>
);

You need to pass the <Link> class as a component prop for the BottomNavigationAction. This way you preserve the integrity of the parent component without disrupting it's CSS classes.
Share:

Contributors

Powered by Blogger.