Having a hard time trying to figure this out.
I Have 2 Components
From component 2 i want to go back to component 1 but have the filters still in place?
How can i acheive this?
I've tried
this.props.history.push('/1');
It goes back but doesn't keep the filters?
export default class FilterComponent extends React.Component {
constructor(props) {
super(props)
this.state = {name:[]}
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/todos")
.then((response) => response.json())
.then(
(data) => data.map(e =>
this.setState({name:[...this.state.name, e.id]})
))
}
onTrigger = (event) => {
this.props.parentCallback(event.target.value);
event.preventDefault();
}
render() {
if(this.state.name.length < 1) {
return (
<div>
<p1> Loadings</p1>
</div>
)
} else {
return (
<div className="contactfForm">
<select onChange={this.onTrigger}>
<option> ID </option>
{this.state.name.map((result)=>(<option title={result}>{result}</option>))}
</select>
I guess you are rendering the filters twice, inside component1 and again inside component2. If you want to navigate and preserve the state, you have two react-based options, and a JS one:
MOVING FILTERS OUTSIDE ROUTER SWITCHER
If you render the filters outside the Switcher of the router, when changing route only the component1 and component2 will rerender, but not the filters.
STORING FILTERS STATE IN A GLOBAL STATE
If rendering the filters outside the Switcher of your Router is not feasible (Because maybe the filters are not rendered in every page of your app) you could save the filter state in a global state (Using for example, React Contexts, see https://reactjs.org/docs/context.html; or Redux).
If you use React Contexts, you could create the provider ouside the router, and inside the Filters component retrieve and modify its values. This way you will mantain the state between components.
SAVING FILTER STATE IN LOCAL STORAGE
If you want to preserve the state also when refreshing the page, you could store the filter state in the Local Storage of the Browser. Every time the Filters component is rendered, you would retrieve the value from the Local Storage, and every time the filters are modified, you would save it. That will also make that when changing the page, as the Local Storage is mantained, the filter state is mantained too.