I'm trying to route my search field to this route:
App.js
class App extends Component {
render() {
return (
<div className="App">
<Header />
<Switch>
<Route exact path='/:q' component={SearchPage} /> //trying to route here
</Switch>
<Footer />
</div>
);
}
}
SearchField.js
import React from 'react'
import { withRouter } from 'react-router-dom'
class SearchField extends React.Component {
constructor(props) {
super(props)
this.state = {
query: ''
}
}
handleChange = event => {
const {name, value, type, checked} = event.target
type === "checkbox" ? this.setState({ [name]: checked }) : this.setState({ [name]: value })
}
handleSubmit = event => {
event.preventDefault()
this.props.history.push(`/${this.state.query}`) //my routing attempt using history.push
}
render() {
return (
<div>
<form className="form-inline my-2 my-lg-0" onSubmit={this.handleSubmit}>
<input
className="form-control mr-sm-2"
type="search"
name="query"
onChange={this.handleChange}
value={this.state.query}
placeholder="Search"
aria-label="Search"
/>
<button className="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
)
}
}
export default withRouter(SearchField)
So whenever I type the query onto the search field, it correctly displays it on the address bar like this:
but the front-end stays intact without changing the query (and no console errors either - completely clean). It's only when I refresh the page is my new query safe
, for example, comes into play. However, I need it to auto-refresh whenever I fire the enter or press the Search
button on my query without the need of manually refreshing the page to see my query results.
I've read this post quite diligently and I've tried all these steps, but I'm still unsuccessful with any approach that I've read.