Home » Reactjs » React-Router v4 onEnter replacement

React-Router v4 onEnter replacement

Posted by: admin January 29, 2018 Leave a comment

Questions:

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);
Answers:

My current solution is to put extra code in render function and not to use component property.

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

Questions:
Answers:

I want to suggest a bit 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 />
        }
    }
}

Questions:
Answers:

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 )} />