Home > Software design >  Move between pages without losing pages content - React JS
Move between pages without losing pages content - React JS

Time:09-26

I'm trying to navigate between pages without losing pages data. For instance, I have a page that contains many input fields, if a user filled all these fields and tried to move to another page and return back to the first one, all the inputs are gone. I am using react-router-dom but didn't find out a way to prevent that.

What I've done till now :

 import { Route, Switch, HashRouter  as Router } from "react-router-dom";
<Router>
     <Switch>
          <Route path="/home" exact component={Home} />
          <Route path="/hello-world" exact component={HellWorld} />
     </Switch>
</Router>

Home Component :

  navigateToHelloWorld= () => {
    this.props.history.push('/hello-world')
  };

Hello World Component :

this.props.history.goBack();

CodePudding user response:

I don't know that that can be supported in such generality. I would just store all state variable values in localStorage, and restore from there when values are present on component render (when using useState then as the default value). Something like this:

const Home = () => {
  const [field, setField] = useState(localStorage.field || '');

  const handleUpdate = (value) => {
    setField(value);
    localStorage.field = value;
  }

  // also add a submit handler incl. `delete localStorage.field`;
 
  return ... // your input fields with handleUpdate as handler.  
}

CodePudding user response:

Generally, all you need to do is to store your data in someplace, either a component that doesn't unmount, like the component you are handling your routes in, which is not a good idea actually but it works!

another way is to use some kind of state manager like 'mobx','redux','mst', or something which are all great tools and have great documentation to get you started

another alternative is to store your data in the browser, for your example session storage might be the one to go for since it will keep data until the user closes the tab and you can read it in each component mount.

  • Related