I'm coming from AngularJS world and start some days ago writing my first React App with react-router
, in AngularJS I do:
app.directive('Loading', function($rootScope, $timeout) {
return {
restrict: 'E',
replace: true,
template: '<p>Loading</p>'
link: function(scope, element) {
$rootScope.$on('$routeChangeStart', function(event, currentRoute, previousRoute) {
element.removeClass('ng-hide');
});
$rootScope.$on('$routeChangeSuccess', function() {
element.addClass('ng-hide');
});
}
};
});
and then I just add <Loading></Loading>
. So now in my React App I have:
class App extends Component {
render() {
return (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</div>
</Router>
);
}
}
and my two components are simple:
class Home extends Component {
render() {
return (
<h1>Home</h1>
);
}
}
class About extends Component {
render() {
return (
<h1>About</h1>
);
}
}
Can I do this without using reduxJS?
import React, { useState, useEffect } from 'react'; const App = () => { const [loading, setLoading] = useState(false); useEffect(() => { setLoading(true); setTimeout(() => { setLoading(false); }, 2000); }, []); return ( <div className="container"> {loading ? ( <div className="loader-container"> <div className="spinner" ...
here is my solution using react hooks. import React, { useEffect } from 'react'; import NProgress from 'nprogress'; import 'nprogress/nprogress. css'; const Loading = () => { useEffect(() => { NProgress. start(); return () => { NProgress.
React Router is a standard library for routing in React. It enables navigation between views from different components in a React application, allows the browser URL to be changed, and keeps the UI in sync with the URL.
you can use a High Order Component in react to do this in a generic way.
Look is a example:
https://github.com/thejameskyle/react-loadable
If you fetching some data I made a small package react-router-loading that allows you to show loading indicator and load some data before switching the screen.
Just use Switch
and Route
from this package instead of react-router-dom
:
import { Switch, Route } from "react-router-loading";
Add loading
props to the Route where you want to wait something:
<Route path="/about" component={About} loading/>
And then somewhere at the end of fetch logic in About
component add loadingContext.done();
:
import { LoadingContext } from "react-router-loading";
const loadingContext = useContext(LoadingContext);
const loading = async () => {
//loading some data
//call method to indicate that loading is done and we are ready to switch
loadingContext.done();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With