2

I have a component that creates buttons with information from an array, when the user clicks on the button I want to pass the information from this array to a function, but I'm getting '[Object Object]', how do I pass the array and access the elements in the function?

Function:

handleClick (e) {
        const { value } = e.currentTarget
        console.log(value)
    };

Component render:

render () {
        return (
            <div>
                {this.state.enrollments.map(item => (
                    <div key={item.id}>
                        <button value={item} onClick={this.handleClick}>
                            {item.enrollment}
                        </button>
                     </div>
                ))}
            </div>
        )
    }

Array passed to map:

0: {id: 1, evaluation_flag: false, enrollment: "2019.1", user_id: 2}
1: {id: 2, evaluation_flag: false, enrollment: "2019.2", user_id: 2}

In the handleClick function I want to access the values, type: value.id or value.user_id.

1 Answer 1

6

You can create an arrow function if you want, and your code would become:

<button value={item} onClick={(e) => this.handleClick(e, item)}>
  {item.enrollment}
</button>

And then obviously modify the handleClick function to accept a second parameter, item.

Basically, what the (e) => handleClick(e, item) does is create the following function in place:

function (e) {
  return handleClick(e, item);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Your example is missing a closing paren. onClick={(e) => this.handleClick(e, item)}
I exclude the value to stay clean, <button onClick={(e) => this.handleClick(e, item)}>. Worked very well!!

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.