I'm currently trying to build a simple react-redux app that has student and campus data in the backend. OnEnter used to work here, but it doesn't exist in the new react-router.
This app tries to load initial data at the start instead of doing a componentDidMount in each actual component. Is that the recommended approach, or are there alternative patterns that I'm not aware of?
/* -------------------< COMPONENT >------------------- */
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Home from './components/Home';
import Students from './components/Students';
const Routes = ({ getInitialData }) => {
return (
<Router>
<div>
<Route exact path="/" component={Home} onEnter={getInitialData} />
<Route path="/students" component={Students} />
<Route path="*" component={Home} />
</div>
</Router>
);
};
/* -------------------< CONTAINER >-------------------- */
import { connect } from 'react-redux';
import receiveStudents from './reducers/student';
import receiveCampuses from './reducers/campus';
const mapState = null;
const mapDispatch = dispatch => ({
getInitialData: () => {
dispatch(receiveStudents());
dispatch(receiveCampuses());
}
});
export default connect(mapState, mapDispatch)(Routes);
react-dom : ReactDOM.render has been deprecated. Using it will warn and run your app in React 17 mode. react-dom : ReactDOM.hydrate has been deprecated. Using it will warn and run your app in React 17 mode.
The project is deprecated, as noted on the react-router-redux github repo. You can still use it if you want, but you may have some fears using a deprecated library in production.
And the React Router version 6, the latest release is finally here! It first launched in an alpha version in early 2021 and is now in a stable release. It has created a lot of buzz in the React community after its release.
My current solution is to put extra code in render function and not to use component property.
<Route exact path="/" render={() => {
getInitialData();
return <Home />;
} } />
I want to suggest a bit different approach. Using class inheritance you can implement your own router.
import React from 'react';
import {Redirect, Route} from 'react-router';
/**
* Class representing a route that checks if user is logged in.
* @extends Route
*/
class AuthRequiredRoute extends Route{
/**
* @example <AuthRequiredRoute path="/" component={Products}>
*/
render() {
// call some method/function that will validate if user is logged in
if(!loggedIn()){
return <Redirect to="/login"></Redirect>
}else{
return <this.props.component />
}
}
}
One solution is to use HOC
function preCondition(condition, WrappedComponent) {
return class extends Component {
componentWillMount() {
condition()
}
render() {
<WrappedComponent {...this.props} />
}
}
}
<Route exact path="/" component={preCondition(getInitialData, Home )} />
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