---------App.js------------------------
import "./styles.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Info from "./Info.js";
import Start from "./Start.js";
import End from "./End.js";
export default function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/" exact component={Start} />
<Route path="/Info" component={Info} />
<Route path="/End" component={End} />
</Switch>
</Router>
</div>
);
}
---------Start.js------------------------
import React from "react";
import { Link } from "react-router-dom";
export default class Start extends React.Component {
render() {
return (
<div>
<h1>Welcome!</h1>
<Link to="/Info">
<button>Next</button>
</Link>
</div>
);
}
}
---------Info.js------------------------
import React from "react";
import { Link } from "react-router-dom";
import arg from "./Infos.json";
export default class Info extends React.Component {
constructor() {
super();
this.state = {
i: 0
};
}
clickNext = () => {
this.setState({ i: this.state.i + 1 });
};
clickBack = () => {
this.setState({ i: this.state.i - 1 });
};
arr = arg.map((elem) => elem);
render() {
return (
<div>
<h1>{this.arr[this.state.i].info}</h1>
<Link to={this.state.i > 0 ? "/Info" : "/"}>
<button type="button" onClick={this.clickBack}>
Back
</button>
</Link>
<Link to={this.state.i < this.arr.length - 1 ? "/Info" : "/End"}>
<button type="button" onClick={this.clickNext}>
Next
</button>
</Link>
</div>
);
}
}
---------End.js------------------------
import React from "react";
import { Link } from "react-router-dom";
export default class End extends React.Component {
render() {
return (
<div>
<h1>End!</h1>
<Link to="/Info">
<button>Back</button>
</Link>
</div>
);
}
}
---------Infos.json------------------------
[
{
"info": "info 1"
},
{
"info": "info 2"
},
{
"info": "info 3"
},
{
"info": "info 4"
}
]
So I have: HomeScreen ⇾ Info1 ⇾ Info2 ⇾ Info3 ⇾ EndScreen
Navigating between each of them works perfectly using simple buttons and Router, Switch, Link.
Between InfoScreen-Instances (which later is going to be fetched from an API) is being navigated using one index (array-index) which is being incremented or decremented according to where we are.
My problem is in the EndScreen-Component where I have a back-button, which should take me back to the last Info-Instance (in this example: Info3). The problem is, when I press the back-button in the EndScreen, the first Info-Instance with index 0 (in this example: Info1) is showing up again.
This means the index manipulated in the Info-Component is not being saved, so that I can go back to the same component with this index, when I try to go back from other components (in this example: EndScreen) to the last rendered Info-Component-Instance.
I am using class components (also tried with function components) and I have been trying since long time with too many ways but still have no clue how to do it.
Can anybody suggest how to exactly navigate properly through components???