React-router v4 onEnter replacement

I am currently trying to create a simple response-redux application with student and campus data in the backend. OnEnter worked here, but it does not exist in the new reaction router.

This application tries to load the source data at the beginning, rather than making a DidMount component in every valid component. Is this the recommended approach or are there alternative patterns that I don't know about?

/* -------------------< 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); 
+8
reactjs react-router redux-thunk
source share
3 answers

My current solution is to add extra code to the rendering function and not use the component property.

 <Route exact path="/" render={() => { getInitialData(); return <Home />; } } /> 
+12
source share

I want to offer a slightly different approach. Using class inheritance, you can implement your own router.

 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 /> } } } 
+7
source share

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 )} /> 
+5
source share

All Articles