Search code examples
reactjsmaterial-uireact-routerreact-router-dom

Link in Material UI and React Router Dom


It needs to look like the <Link> in Material-UI but the problem is that its doing a refresh when navigating it. So what I did is use the <Link> of the react-router-dom and put the <Link> of Material-UI as its component.

The problem is with the UI, I wanted to follow the UI of the MUI Link not the react-router-dom. Is there a shorter way without modifying much of its CSS?

import { Link as LinkBase } from '@mui/material';
import { Link } from 'react-router-dom';

      <Link
        component={LinkBase}
        to={`/products/${id}`}
      >
        {name}
      </Link>

Solution

  • You can pass the link of react-router-dom in the components property of the @mui/material

    import './App.css';
    
    import { Link as LinkBase } from '@mui/material';
    import { Link, BrowserRouter, Routes, Route } from 'react-router-dom';
    
    function App() {
      return (
        <BrowserRouter>
          <Routes>
            <Route
              path="/"
              element={
                <LinkBase component={Link} to="/home">
                  home
                </LinkBase>
              }
            />
            <Route path="/home" element={<h1>a</h1>} />
          </Routes>
        </BrowserRouter>
      );
    }
    
    export default App;