2

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
      ),
    });
  };
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Cococrunch
  • 67
  • 1
  • 12
  • 2
    A `div` is not allowed as a child of a `button` according to the html5 specs. Only [phrasing content](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content). – trixn Jul 22 '20 at 12:38
  • Does this answer your question? [What is the exact difference between currentTarget property and target property in javascript](https://stackoverflow.com/questions/10086427/what-is-the-exact-difference-between-currenttarget-property-and-target-property) – Emile Bergeron Jul 22 '20 at 13:20

1 Answers1

5

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.

Y Allaban
  • 112
  • 1
  • 1
  • 8