0

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>

        )
    }
}
0

1 Answer 1

1

If you remove the blur event, the alert will pop up (See this sandbox). In other words, the onBlur takes precedence over onClick. It first hides the list, and then tries to handle the click, but by then the list is already removed from the DOM, so you don't see the item getting selected. You need to revise your logic. Maybe use a traditional <select>?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.