Steve
Steve

Reputation: 122

How to maintain state using react-router

I have a react app with a main App.js file that holds my initial state. I then have some routes setup to navigate around my application.

In one of the routes I have a button which when pressed processes a set state. I know that this works as I've console logged the change in state. However, it then also calls:

window.location.href = '/';

This then routes us to our homepage. However, once the homepage renders the state reverts to its initial setup as detailed in App.js. I don't know why state is not being maintained once I'm rerouted to another part of the website. Given I'm using react-router does this mean I need to use redux to handle the app's state?

Upvotes: 4

Views: 16347

Answers (1)

siddharth lakhara
siddharth lakhara

Reputation: 307

This is happening because you are redirecting using window object rather than react router. You don't need to use redux. To use react router, you need to use its history method. And then use it as follows, inside a component:

this.props.history.push('/');

For example take the following react functional component:

const LoginButton = ({ history }) => (
  <button onClick={() => { history.push('/login'); }} >
    Log in
  </button>
);

Explanation: The above component, destructures history from props, and then use it to redirect to login page

Link to history api: https://reacttraining.com/react-router/web/api/history

Upvotes: 10

Related Questions