Skip to content

Instantly share code, notes, and snippets.

@erikras
Last active September 23, 2020 03:03
Show Gist options
  • Save erikras/8e169927ce145b2260a2735d4cbdab3a to your computer and use it in GitHub Desktop.
Save erikras/8e169927ce145b2260a2735d4cbdab3a to your computer and use it in GitHub Desktop.
A search box that replaces a query parameter in the url
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>
)
}
}
@erikras
Copy link
Author

erikras commented May 9, 2016

The q param name could be abstracted away as a prop, but I don't care about that.

@swyxio
Copy link

swyxio commented Sep 23, 2020

hi erik found you on google lol

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment