Dropdown onclick isn't getting called when item selected in react

Related searches

The onlick event handler isn't getting called when I select dropdown item.

I am generating dropdown in a loop in componentDidMount() and passing event handler function "showDataTypeName" to onclick while generating dropdown but for some reason its not getting called. Any idea why this is failing?

Below is my component where I am generating dropdown

export class GenerateParams extends Component{
    constructor(props){
        super(props);
        this.state = {
            dataTypeName: "Select Type",
            rows: []
        }
    }

    componentDidMount(){
        let dataTypes = [];
        let content = this.state.rows.slice();    
        if(typeof this.props.apiPropertiesSuccess != 'undefined' && this.props.apiPropertiesSuccess.size > 0){
            this.props.apiPropertiesSuccess.map((type, i) => {
                dataTypes.push(<li key={type.get('id')}><a onClick = {this.showDataTypeName(type.get('id'), type.get('name'))}> {type.get('name')} </a></li>)
            });
        }


        for(let i=0; i < this.props.params.length; i++){
            content.push(<div>
                <div className="col-md-6">
                    <TextInput size="medium" value={this.props.params[i]} readOnly/>
                </div>
                <div className="col-md-6">
                    <div className="dropdown">
                        <button className="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">{this.state.dataTypeName}
                            <span className="caret"></span>
                        </button>
                        <ul className="dropdown-menu">
                            {dataTypes}
                        </ul>
                    </div>
                </div>
            </div>)
        }

        this.setState({rows:content})
    }
    showDataTypeName = (id, name) => {
        console.log("id, name", id, name)
        this.props.handleDataTypes(id, name);
        this.setState({
            dataTypeName: name
        });
    }

    render(){
        const {params, apiPropertiesSuccess} = this.props;     

        return(
            <div>
                {this.state.rows}
            </div>
        )
    }
}

Note: Accepting xadm's answer because his solution was posted first. Thanks to @UtkarshPramodGupta and @anshul as well.

the simplest solution (react docs): this.showDataTypeName = this.showDataTypeName.bind(this) in constructor

If you prefer using arrow function (automatic binding) you can use: onClick={ () => this.showDataTypeName(type.get('id'), type.get('name')) }

But keep in mind that binding in render is not the optimal for performance reasons.

How To Create a Dropdown Menu With CSS and JavaScript, In the next example the hover element is a <p>, and the dropdown content is a <​span>: <button onclick="myFunction()" class="w3-button w3-black">Click Me! Create a Dropdown in React that Closes When the Body is Clicked. Intro. One common interaction with dropdowns is closing when anything else on the page is clicked. Within React though with controlled dropdowns that are shown by updating state you need to add additional code in order to properly setup this interaction.

You are not calling onclick the right way. Below is the right code:

<a onClick = {this.showDataTypeName.bind(this, type.get('id'), type.get('name'))}>

W3.CSS Dropdowns, Dropdown Button onClick with Html, CSS and Javascript - Simple jQuery Tutorial For Duration: 8:25 Posted: Mar 24, 2018 1) Open Drop Down Menu software and click "Add item" and "Add submenu" buttons situated on the Drop Down Menu Toolbar to create your menu. You can also use "Delete item" to delete some buttons. 2) Use ready to use Templates. To do it just select theme you like in the "Templates" list.

you have to specify onClick event on button click

<div className="dropdown">
    <button onClick={() => console.log('yeah')} className="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">{this.state.dataTypeName}
                                <span className="caret"></span>
                            </button>
                        <ul className="dropdown-menu">
                            {dataTypes}
                        </ul>
                    </div>

Dropdown Button onClick with Html, CSS and Javascript, I'm raising a click event to a dropdown list controlled component, but the click event is not working. The component looks like this: const  Once you click on any of the parent menu - it will show its own sub level in the drop down. When you click on any other Parent - the previous Drop down will disappear and the new Drop down will appear.

You need to edit your function as below.

showDataTypeName = (id, name) => () => {
        console.log("id, name", id, name)
        this.props.handleDataTypes(id, name);
        this.setState({
            dataTypeName: name
        });
    }

Edit

A better approach to have performance improvement, would be to bind the click handler to the ul element and make use of event propagation to handle the click function. I have updated the code to reflect the same.

export class GenerateParams extends Component{
    constructor(props){
        super(props);
        this.state = {
            dataTypeName: "Select Type",
            rows: []
        }
    }

    componentDidMount(){
        let dataTypes = [];
        let content = this.state.rows.slice();    
        if(typeof this.props.apiPropertiesSuccess != 'undefined' && this.props.apiPropertiesSuccess.size > 0){
            this.props.apiPropertiesSuccess.map((type, i) => {
                dataTypes.push(
                    <li key={type.get('id')} id={type.get('id')} name=type.get('name')>
                    {type.get('name')}
                </li>);
            });
        }


        for(let i=0; i < this.props.params.length; i++){
            content.push(<div>
                <div className="col-md-6">
                    <TextInput size="medium" value={this.props.params[i]} readOnly/>
                </div>
                <div className="col-md-6">
                    <div className="dropdown">
                        <button className="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">{this.state.dataTypeName}
                            <span className="caret"></span>
                        </button>
                        <ul className="dropdown-menu" onClick={this.showDataTypeName}>
                            {dataTypes}
                        </ul>
                    </div>
                </div>
            </div>)
        }

        this.setState({rows:content})
    }
    showDataTypeName = (event) => {
        let id = event.target.id;
        let name = event.target.name;
        console.log("id, name", id, name)
        this.props.handleDataTypes(id, name);
        this.setState({
            dataTypeName: name
        });
    }

    render(){
        const {params, apiPropertiesSuccess} = this.props;     

        return(
            <div>
                {this.state.rows}
            </div>
        )
    }
}

React - onClick does not work with option tag? - JavaScript, This allows a nested Dropdown to close the top-level Dropdown but it is calling functions provided by other components as well. In this case, the  This cannot be done in the same way as a radioButtonList, for a dropdownlist, the correct attribute event name is "onchange" instead of "onclick". The event should be attached to DropDownList Itself and not the items as follows:

onClick stopPropagation() ignored on Dropdown, DropdownButton , A pure CSS onclick context menu. Context menus are one of those very useful UI widgets that still haven’t reached the HTML spec. There have been attempts, but for now everyone tends to make its own custom implementation.

Learn how to create a clickable dropdown menu with CSS and JavaScript. A dropdown menu is a toggleable menu that allows the user to choose one value from a predefined list: Create a dropdown menu that appears when the user clicks on a button. Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element.

Sorry to bring up a closed issue, but the dropdown is not working (upon click) with Bootstrap 3.0.3 for me either. Dropdown js is already included in bootstrap.js, and all js loads fine.

Comments
  • I no need to bind function/object because I am using arrow function.
  • in map, not in onclick
  • you don't ;) you have onClick = {this.showDataTypeName arrow fn would look like onClick={ () => this.showDataTypeName (....) }
  • Hey sorry xadm. placing () => worked for me. Kindly put this as an answer I will accept it
  • 'Nice' - you could accept it, it was a solution, not first answer alone but as a thread (with comments). It's also a cleaner, more readable, simply better than binding in render/onClick (upvoted?) and possibly better (not optimal, not better than accepted one) than using arrow function in onClick. Better than 2 other solutions and downvoted??
  • I no need to bind showDataTypeName when it is already an arrow function. It is working fine now after adding "() =>". <a onClick = {() => this.showDataTypeName(type.get('id'), type.get('name'))}> {type.get('name')} </a>. xadm comment is correct
  • It's not about binding it. It's about that onClick handler takes the name of the function and not its return value. In your code, you are executing the function on the line itself and that would assign the return value of the showDataTypeName function and not the function itself. Just try to do it the way I have suggested and It would work I promise. :)
  • I agree with that but just placing "() =>" in onClick = {() => this.showDataTypeName(type.get('id'), type.get('name'))} without binding working for me.
  • Yeah, that is also one way to do that if you don't wanna use bind. :)
  • I already have onClick handler to a tag when I am pushing to dataTypes. It is working fine now after adding "() =>". <a onClick = {() => this.showDataTypeName(type.get('id'), type.get('name'))}> {type.get('name')} </a>
  • why do you think this ' = (id, name) => () => ' makes sense ? ... Calling an arrow function to call an arrow function ?
  • It is working fine now after adding "() =>". <a onClick = {() => this.showDataTypeName(type.get('id'), type.get('name'))}> {type.get('name')} </a>
  • @HemadriDasari , even though it works you should avoid using arrow functions in the render functions. Refer this -> medium.freecodecamp.org/…
  • @AnshulBansal thanks for pointing me to the article. You used two arrows isn't that arrow function?
  • @HemadriDasari, yes it uses arrow function but not inside the render function per se . The two arrow functions which I have used is used to create a closure. In simple terms the first function returns an anonymous function which gets called later on when click action is performed. This is another way to use arrow functions when we need to pass arguments to it. @l4b0mb4 :)