4

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?

Steve
  • 122
  • 1
  • 2
  • 9
  • 1
    you should use the history API that gets imported with react-router: https://reacttraining.com/react-router/web/api/history – Hunter McMillen Oct 09 '18 at 17:02
  • 1
    Whenever a component is initialized, the state of that component is initialized as well. Since you are navigating to a new component, your state will be reinitialized. If you're looking to maintain props at the parent level and make changes from the child, check out this post: https://stackoverflow.com/questions/22639534/pass-props-to-parent-component-in-react-js?answertab=active#tab-top I would also recommend checking out react-router docs for a better understanding of how to navigate and pass props to and from components: https://reacttraining.com/react-router/ – Ariel Salem Oct 09 '18 at 17:20

1 Answers1

10

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

siddharth lakhara
  • 307
  • 1
  • 5
  • 12