I have a SPA that has multiple routes. Each of these routes are parent components to 2 children (a form component and a table component, that displays data fetched from an API). The goal is to be able to come back to the form with the fields populated as before if a user navigates away from it.
Here's what I have so far. My index.js
:
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
App.js
return (
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/onDemandProductSearch" component={OnDemandProductSearch} />
</Switch>
);
OnDemandProductSearch.js
component has 2 children as mentioned above. I only display the form and once parameters on the form are selected, display the table with the fetched data.
class OnDemandProductSearch extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
isSearched: false
};
};
onFiltersSelected = (products, queryParams) => {
this.setState({
products: products,
isSearched: true
});
this.props.history.push({
search: queryParams
});
};
render() {
return (
<div>
<Header />
{this.props.history.location.search === "" ?
<OnDemandProductSearchMenu onFiltersSelected={this.onFiltersSelected} /> :
<InstanceList products={this.state.products} />}
</div>
);
};
};
OnDemandProductSearchMenu.js
,
fetch(`${apiURL}/simple-products/search`, {
// body here
})
})
.then((response) => {
// more logic here
})
.then((data) => {
// I build a parameter string here I want the table component to be rendered with. This is important to the app
var paramString = `.....`;
this.props.onFiltersSelected(data, paramString);
})
.catch((error) => {
console.log(error);
});
I read the docs for react-router, but wasn't clear on how the history
works exactly. I understand a route needs to be pushed to the history, but how do I tackle it since the form component won't have access to history
?