Cococrunch
Cococrunch

Reputation: 67

onClick and event.target not working react

I plan to make a button that updates the state when clicked. Inside the button there is a img and div. The onClick on trigers when I clicked on the button but not when I clicked the img or div. Anyone know how to solve this issue as I wan the user to click anywhere on the button (including the img and div). My jsx code is:

<div
                className={
                  'flex flex-row flex-wrap justify-around border-2 rounded border-dashed'
                }>
                {categoryLeft.map((category) => (
                  <button
                    onClick={this.addCategory}
                    type='button'
                    value={category}
                    name={category}
                    className={
                      'flex bg-teal-600 my-2 mx-1 w-auto h-auto hover:bg-teal-400 text-white font-bold px-1 rounded'
                    }>
                    <div className={'self-center'} value={category}>
                      {category}
                    </div>
                    <img
                      className={'float-right ml-1 self-center w-5 h-5'}
                      value={category}
                      src={CloseImg}
                    />
                  </button>
                ))}
              </div>
            </div>

My method is:

 addCategory = (e) => {
    console.log(e.target);
    console.log(this.state.categoryLeft);
    this.setState({
      categoryUsed: [...this.state.categoryUsed, e.target.value],
      categoryLeft: this.state.categoryLeft.filter(
        (cat) => cat !== e.target.value
      ),
    });
  };

Upvotes: 2

Views: 3134

Answers (1)

Y Allaban
Y Allaban

Reputation: 112

You could try e.currentTarget.value instead of e.target.value.

From the DOM Event documentation:

Event.currentTarget Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

Upvotes: 5

Related Questions