Home > database >  Back button not loading previous component
Back button not loading previous component

Time:10-02

The <Redirect /> inside <App /> does render test from the router, but the back button doesn't take me back to the <App />.

index.js

<Router>
    <Switch>
        <Route path="/documents">
            <>test</>
        </Route>
        <Route path="/">
            <App />
        </Route>
    </Switch>
</Router>

App.tsx

function App() {
    const [isClicked, setIsClicked] = useState(false);

    return (
        <div className="App">
            <GetStarted buttonClicked={setIsClicked} />
            {isClicked && <Redirect from="*" to="/documents" />}
        </div>
    );
}

GetStarted.tsx

function GetStarted(props: Props) {
    return (
        <div
            onClick={(): void => {
                props.buttonClicked(true);
            }}
        >
            CONTINUE
        </div>
    );
}

So, the page loads, I click "continue" and my browser url bar reads http://localhost:3000/documents and correctly renders "test". I would expect that if I hit back, it would render <App /> again, but it does not. It stays at http://localhost:3000/documents.

CodePudding user response:

No need to use <redirect/> you can use <Link/> example: here

Example edit App.tsx

function App() {
 return (
    <div className="App">
        <GetStarted/>
    </div>
);}

and edit GetStarted.tsx

function GetStarted() {
 return (
   <Link to="/documents">
     <div>
        Click and redirect to Test.tsx
     </div>
   </Link>
);}

you can create one view Test.tsx for back to view App.tsx

function Test() {
  return (
    <Link to="/">
      <div>
        Click for come in back to App.tsx
      </div>
    </Link>
 );
}

The View Test.tsx you must call her in file index.js

<Router>
 <Switch>
    <Route path="/documents">
        <Test />
    </Route>
    <Route path="/">
        <App />
    </Route>
 </Switch>
</Router>
  • Related