Im running React and Rails 5.2 with webpacker.
I have an ElasticSearch Search bar at the top of the page, and I am having trouble sending the proper request to the back end, and allowing the rails back end to process the search request.
We are no where near ready to have this as a SPA right now, but I cant seem to get the params to be populated.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {asyncContainer, Typeahead} from 'react-bootstrap-typeahead';
const AsyncTypeahead = asyncContainer(Typeahead);
class SearchBar extends Component {
constructor(props) {
super(props)
this.state = {
options: ['Please Type Your Query'],
searchPath: '/error_code/search',
selected: [""],
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
searchErrorCodes(term) {
fetch(`/error_code/auto?query=${term}`)
.then(resp => resp.json())
.then(json => this.setState({options: json}))
}
handleChange(error_code_name) {
let newValue = error_code_name
this.setState({
selected: newValue
});
this.setState({
searchPath: `/error_code/search?error_code=${this.state.selected}`,
});
console.log(`This is the new searchPath is ${this.state.searchPath}`);
}
handleSubmit(e) {
alert(`submitted: ${this.state.selected}`);
// event.preventDefault();
}
render() {
return (
<div>
<form ref="form"
action={this.state.searchPath}
acceptCharset="UTF-8"
method="get"
onSubmit={e => this.handleSubmit(e)}
>
<AsyncTypeahead
onSearch={term => this.searchErrorCodes(term)}
options={this.state.options}
className="search"
onClick={e => this.handleSubmit(e)}
selected={this.state.selected}
onChange={e => this.handleChange(e)}
/>
<button
action={this.state.searchPath}
acceptCharset="UTF-8"
method="get"
type="submit"
className="btn btn-sm btn-search">
<i className="fa fa-search"></i>
</button>
</form>
</div>
)
}
}
ReactDOM.render(<SearchBar/>, document.querySelector('.search-bar'));
Everything is rendering correctly, but the input is not being sent properly to the controller.