Last active
September 23, 2020 03:03
-
-
Save erikras/8e169927ce145b2260a2735d4cbdab3a to your computer and use it in GitHub Desktop.
A search box that replaces a query parameter in the url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, PropTypes } from 'react' | |
import { withRouter } from 'react-router' | |
import queryString from 'query-string' | |
@withRouter | |
export default class SearchBox extends Component { | |
static propTypes = { | |
router: PropTypes.object.isRequired | |
} | |
constructor(props) { | |
super(props) | |
this.state = { search: '' } | |
this.handleSubmit = this.handleSubmit.bind(this) | |
this.handleChange = this.handleChange.bind(this) | |
} | |
getLocation() { | |
// this is the best way to get the current search value? | |
let location | |
this.props.router.listen(routerState => { | |
location = routerState | |
})() // immediately unlisten | |
return location | |
} | |
componentWillMount() { | |
const { search } = this.getLocation() | |
this.setState({ search: queryString.parse(search).q || '' }) | |
} | |
handleSubmit(event) { | |
event.preventDefault() | |
const { router } = this.props | |
const { pathname, search } = this.getLocation() | |
const query = queryString.parse(search) | |
if (this.state.search) { | |
query.q = this.state.search | |
} else { | |
delete query.q | |
} | |
const string = queryString.stringify(query) | |
router.push({ | |
pathname, | |
search: string ? `?${string}` : '' | |
}) | |
} | |
handleChange(event) { | |
this.setState({ search: event.target.value }) | |
} | |
render() { | |
const { search } = this.state | |
return ( | |
<form onSubmit={this.handleSubmit}> | |
<input type="text" | |
placeholder="Search..." | |
value={search} | |
onChange={this.handleChange}/> | |
</form> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
q
param name could be abstracted away as a prop, but I don't care about that.