I am new in react.
I want to show a list based on a state. If showList is true, show the list and vice versa. But when I click on list element the selectItem method does not fired and the list disappears.
But toggleList method is working, although both methods are handled same way. I tried making selectItem as anonymous method, also bind it in constructr, but no luck.
Can anybody give me a working code for this ?
import React from 'react';
export default class Select extends React.Component {
constructor(props){
super(props);
this.state={
list:[],
showList:false,
selectedItem:''
}
// this.selectItem = this.selectItem.bind(this)
}
toggleList(e, toggle){
this.setState({showList:toggle})
}
selectItem(e, item){
alert('')
this.setState({selectedItem:item.name})
}
render(){
let {showList,selectedItem} = this.state;
let _this = this;
let arr = [
{
name:'Piyush',
value: '2'
}
]
return (
<div>
<input type="text"
onClick={e=>this.toggleList(e, true)}
onBlur={e=>this.toggleList(e,false)}
value={selectedItem.name}
/>
{
showList &&
<div style={{backgroundColor:'#fff', color:'#333', zIndex:9999}}>
<ul>
{
arr.map(item=>{
return <li key={item.value} id={item.value} onClick={(e)=>this.selectItem(e)}> {item.name} </li>
})
}
</ul>
</div>
}
</div>
)
}
}