user3717206
user3717206

Reputation: 75

How to get id of button clicked in mapped loop in React

Hi I've been trying to get the id of mapped buttons in react and pass it to a variable in my state.

This is my code

render() {

    let {firstpost, selectedGroup} = this.state;
    let visibleModal = this.showModal;

    var groupList = firstpost.map(function(item, i){

    return (
        <li key={i}>
        <div >
        <button id={myButton+[i]} onClick={visibleModal}>
                btn{firstpost[i]}
            </button>

        </div>
        </li>
    )
    });
return (
    <div>
        {groupList}
         <Modal
                width={'50%'}
                visible={visible}
                onCancel={this.handleCancel}
                footer= {null}
            >

                <Form onSubmit={this.onSubmit}>
                    <span>Are you sure you want to click</span>
                    <Button type="primary" htmlType="submit" style={{margin: '0 0 0 50%'}}>click</Button>
                </Form>

            </Modal>
    </div>

I tried using Jquery like so in my componentsWillMount

let _this = this;
$(":button").click(function (event) {
        _this.setState({idName: $(this).attr('id')});
    });

and I also tried

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
    _this.setState({idName:this.id});
};
}​

But that didn't seem to work and I'm not sure of how else to go about it. Any ideas would be greatly appreciated

Upvotes: 1

Views: 766

Answers (1)

Siu
Siu

Reputation: 1432

If you only want to update the state idName, and do not need reference to each button, you may set state in onClick callback of the button:

var groupList = firstpost.map((item, i) => 
    <li key={i}>
        <div >
            <button onClick={(e) => {
                        this.setState({idName: `myButton${i}`})
                    }}>
                btn{item}
            </button>
        </div>
    </li>
);


By the way, be careful of using just index as key. It can lead to unpredictable rendering issue, because a key is the only thing React uses to identify DOM elements. It is better to assign a unique id to each item in your list and use it as key. Here and here are some articles you may find useful explaining this issue.

Upvotes: 3

Related Questions