I am trying to create a search page in an application with several pages, I use react router v5.
My problem is the following, I would like to return to the previous page when a text field is empty otherwise if there is an entry in the input field, I want to return to the search page ('/search')
I thank you in advance for your help and your answers.
So I used goBack and push props. But the return to the previous page does not work even when the field is empty
My component Routes.js
const Routes = (props) => {
return (
<div>
<Route exact path="/" component={Home} />
<Route
exact
path='/search'
component={() => <Search query={props.text} />}
/>
<Route path="/film/:id" component={MovieDetail} />
<Route path="/FavorisList" component={WatchList} />
<Route path="/search/:search" component={Search} />
<Route path="*" component={NotFound} />
</div>
)}
My component SearchBar.js
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue:'',
};
}
handleChange = (event) => {
if(event.target.value === '') {
this.props.history.goBack()
return;
}
if(event.target.value.length){
this.props.history.push("/search")
this.search(event.target.value)
}
}
search = (query) => {
//search results retrieved with redux
this.props.applyInitialResult(query, 1)
}
render() {
return (
<div>
<input
type="text"
value={this.state.inputValue}
placeholder="Search movie..."
className={style.field}
onChange={this.handleChange.bind(this)}
/>
</div>
);
}
export default SearchBar;
Component App.js
class App extends React.Component {
render(){
return (
<div>
<BrowserRouter>
<NavBar />
<Routes/>
</BrowserRouter>
</div>
);
}
}
export default App;