I have this router animation working on page load but when I use the navbar to navigate it changes the web address but the pages don't change or take extremely long to change.
import React, { useContext } from "react";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, __RouterContext } from "react-router-dom";
import { useTransition, animated } from "react-spring";
import "assets/scss/material-kit-react.scss?v=1.4.0";
// pages for this product
import LandingPage from "views/LandingPage/LandingPage.jsx";
import ProfilePage from "views/ProfilePage/ProfilePage.jsx";
var hist = createBrowserHistory();
const App = () => {
const { location } = useContext(__RouterContext);
const transitions = useTransition(location, location => location.pathname, {
from: { opacity: 0, transform: "translate(100%,0)" },
enter: { opacity: 1, transform: "translate(0%,0)" },
leave: { opacity: 0, transform: "translate(-50%,0)" }
});
return (
<>
{transitions.map(({ item, props, key }) => (
<animated.div key={key} style={props}>
<Router history={hist}>
<Switch location={item}>
<Route path="/profile-page" component={ProfilePage} />
<Route path="/" component={LandingPage} />
</Switch>
</Router>
</animated.div>
))}
</>
);
};
export default App;
This is how my NavLink is structured
<Link
exact
to="/profile-page"
className={classes.link}
activeClassName="active"
>
I tried to recreate your problem. I think your problem could be, that you use Router outside and inside the App as well. Because useContext would not work without an outer router. So the solution is to remove router from the render of the app. Here is my full working example:
import React, { useContext } from 'react';
import { createBrowserHistory } from 'history';
import {
Route,
Switch,
Link,
__RouterContext,
BrowserRouter
} from 'react-router-dom';
import { useTransition, animated } from 'react-spring';
import ReactDOM from 'react-dom';
function App() {
return (
<BrowserRouter>
<Home />
</BrowserRouter>
);
}
// pages for this product
const LandingPage = () => {
return (
<div>
<h1>LandingPage</h1>
<Link to="/profile-page">profile</Link>
</div>
);
};
const ProfilePage = () => {
return (
<div>
<h1>Profile</h1>
<Link to="/">main</Link>
</div>
);
};
const Home = () => {
const { location } = useContext(__RouterContext);
const transitions = useTransition(location, location => location.pathname, {
from: {
position: 'absolute',
width: '100%',
opacity: 0,
transform: 'translate(100%,0)'
},
enter: { opacity: 1, transform: 'translate(0%,0)' },
leave: { opacity: 0, transform: 'translate(-50%,0)' }
});
return (
<>
{transitions.map(({ item, props, key }) => (
<animated.div key={key} style={props}>
<Switch location={item}>
<Route path="/profile-page" component={ProfilePage} />
<Route path="/" component={LandingPage} />
</Switch>
</animated.div>
))}
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
export default App;
You can try it here: https://codesandbox.io/s/sleepy-wozniak-b07jp