Reputation:
When I try and add a onClick="{this.displayResults(false)}" to the the dropdown li, it will not appear. When I try and add the onClick="{this.displayResults(false)} to the Search Results div, it conflicts with the inputs onChange event. Any suggestions on how I can close the dropdown when a user clicks a search result?
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as actions from '../actions';
class Search extends Component {
handleSearchTerm(term) {
if (!term == "") {
this.props.getSearchResults({term});
this.displayResults(true);
} else {
this.displayResults(false);
}
}
displayResults(display) {
if (display === false) {
$( ".search-results" ).css( "display", "none" );
} else {
$( ".search-results" ).css( "display", "block" );
}
}
buildResultsList() {
if (!this.props.searchResults) {
return null;
} else {
const searchResultsList = this.props.searchResults.map(function (result) {
return ([
<div className="dropdown-divider"></div>,
<Link to={`/project-spotlight/${result.uri}`} className="dropdown-item" id="search-result"> <li key={result.urlName}>{result.urlName}</li></Link>
]);
});
return searchResultsList;
}
}
render() {
console.log(this.props.searchResults);
return (
<div className="search-component">
<form className="form-inline nav-search">
<input
className="form-control mr-sm-2"
onChange={(e) => this.handleSearchTerm(e.target.value)}
id="navBarSearchForm"
aria-expanded="false"
aria-haspopup="true"
type="text"
placeholder="What Pod you looking for?"
autoComplete="off">
</input>
</form>
<ul className="dropdown-menu search-results" >
<h5 className="dropdown-header">-Pods-</h5>
{this.buildResultsList()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { searchResults: state.search.searchResult};
}
export default connect(mapStateToProps, actions)(Search);
Upvotes: 0
Views: 86
Reputation: 6546
Add event.preventDefault();
to your handler method
If this method is called, the default action of the event will not be triggered.
import React, { Component } from 'react';
export default class MyComponent extends Component {
handleClick(event) {
event.preventDefault();
//...
}
render() {
return (<button onClick={this.handleClick.bind(this)}>Submit</button>)
}
}
Upvotes: 1