I am having a dropdown list with certain years and showing the current year by default. I want to set an onBlur event to close the dropdown when the user clicks outside. onBlur works fine but my problem is I can't set the currently selected year. the problem here is that when I select a value from the dropdown which is the child of this div, it triggers the onBlur event hence dropdown closes and I can't set value. now, how do I achieve setting onBlur correctly so that selecting elements from the list doesn't trigger onBlur or is there any other way to achieve this.
this is Child component
import React from 'react';
const SelectProjection = (props) => {
let years;
if (props.yearList) {
years = props.yearList.map((year, index) => {
return (
<div
className="dropdown-child"
title="value"
key={index}
role="presentation"
onClick={(e) => props.filterHandler(year)}
tabIndex={0}
>
<span id="dropdown-child-item">{year}</span>
</div>
);
});
} else {
years = <div>Loading....</div>;
}
return (
<div>
<div
id="sort-by"
className={`${props.orderBy} ${
props.open ? 'open' : ' close'
}`}
>
<div className="header" style={{ fontSize: '12px' }}>
Project to year
</div>
<div className="sort-by-dropdown" onBlur={props.hideDropdown} >
<div
className="selected"
id="openProjectionFilter"
onClick={props.showDrop}
onKeyPress={props.showDrop}
tabIndex={0}
role="button"
>
<span id="selected-sort-item">{props.selectedYear} </span>
</div>
<div className="options">
<div
className="dropdown-child"
title="value"
role="presentation"
tabIndex={1}
onClick={() => props.filterHandler()}
>
<span id="dropdown-child-item">{props.selectedYear}</span>
</div>
{years}
</div>
</div>
</div>
</div>
);
}
export default SelectProjection;
this is my parent component
class HealthFilter extends React.Component {
state = { openProjectionFilter: false };
showProjectionList = () => {
this.setState(state => ({
openProjectionFilter:!state.openProjectionFilter }));
};
filterYearHandler = (year) => {
console.log('child clicked')
this.props.handlerYear(year)
this.setState({ openProjectionFilter: false })
}
hideDropdown = (event) => {
console.log('parent clicked')
this.setState({ [event.target.children[0].id]: false })
}
render() {
const { openProjectionFilter } = this.state;
const { boms } = this.props
return (
<div id={'filter'}>
<div id="alert-filter-body" className=''>
<SelectProjection
open={openProjectionFilter}
hideDropdown={this.hideDropdown}
showDrop={this.showProjectionList}
selectedYear={this.props.selectedYear}
filterHandler={this.filterYearHandler}
yearList={this.props.yearList}
/>
<div className="checkboxes" style={{ marginTop: 10 }}>
<div className="filter-button green" role="button" onClick={this.props.submitProjections}>
Calculate
</div>
</div>
</div>
</div>
);
}
}
HealthFilter.propTypes = {};
export default HealthFilter;