TheoG
TheoG

Reputation: 1558

Migrating from React Router v2 to v4

So, I'm currently using react-router v2 as follows:

import { IndexRoute, Router, Route, Redirect } from 'react-router';
import App from './components/App';
  ....
  render () {
    return (
      <ApolloProvider store={store} client={client}>
        <Router history={history}>
          <Route path="/" component={App}>
            <IndexRoute component={PhotoGrid} />
            <Route path="/view/:postId" component={Single}></Route>
            <Route path="/login" component={LoginUser}></Route>
          </Route>
        </Router>
      </ApolloProvider>
    )
  }
}

export default MainApp;

App.js

....
import Main from './Main';

const allPostsCommentsQuery = graphql(All_Posts_Comments_Query, {
  options: {
    cachePolicy: 'offline-critical', 
    fetchPolicy: 'cache-first',
  },
});

function mapStateToProps(state) {
   return {
    auth: state.auth
  };
}

export const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(actionCreators, dispatch);
}

export default compose(
  allPostsCommentsQuery,
  connect(mapStateToProps, mapDispatchToProps)
)(Main);

Main.js

class Main extends React.Component {

  constructor (props) {
    super(props);
  }
  
  componentWillMount () {
    if (!this.props.auth.token){
      this.context.router.push('/login');
    }
  }
  
  render () {
    return (
      <div>
        <h1>
          <Link to="/">Flamingo City</Link>
        </h1>
        { React.cloneElement(this.props.children, this.props) }
      </div>
    );
  }
}

Main.contextTypes = {
  router: function() { React.PropTypes.func.isRequired }
};

export default Main;

How do I convert my current v2 router to v4? What I am not clear on, is the parent nested element:

<Route path="/" component={App}>

In all the v2 -> v4 conversion examples I have seen thus far, none clearly explain what happens to the child elements. Am I expected to place the child elements within the App.js component itself, and if so, in the version of my App.js, how would that work as the first sign of any navigation actually occurs with Main.js?

Upvotes: 2

Views: 1263

Answers (1)

rmartrenado
rmartrenado

Reputation: 1576

Really useful post on github where you can see all the important parts of migrating to v4.

https://gist.github.com/kennetpostigo/7eb7f30162253f995cd4371d85c1e196

Also explaining how to go about child routes. Basically, you are supposed to place a Match inside App.js so this parent component will become responsible for its own part of child routes, an so on with every parent component.

Haven't tried this, let me know how it goes!

Upvotes: 2

Related Questions