skip to Main Content

So Im trying to get the value from a button. This my button:

<button
  className="toggle__btn"
  value={el._id}
  onClick={toggle}
>
     <i className="fa-solid fa-circle-info fs-4"></i>
</button>

This my function:

const toggle = (event) => {
    const id = event.target.value;
    console.log(id);
  };

The problem is I can’t get the value if I click the icon, but I can when I click outside the icon but still inside the button(there is blank space outside the icon). I want it to return the id even when the icon is clicked. How to do so? Why does this happen?

4

Answers


  1. Unlike target, currentTarget remains the same throughout the event propagation, even if the event bubbles up to a parent element. It always refers to the element that the event listener was attached to.

    You can try using currentTarget to refer the element that attached the event. This will retrieve the id from the button element, whether you click on the icon or the blank space inside the button.

    const toggle = (event) => {
      const id = event.currentTarget.value;
      console.log(id);
    };
    
    Login or Signup to reply.
  2. try

    const toggle = (event) => {
        const id = event.currentTarget.value;
        console.log(id);
    };
    

    event.currentTarget tells us on which element the event was attached or the element whose eventListener triggered the event.

    event.target tells where the event started.

    See https://medium.com/@etherealm/currenttarget-vs-target-in-js-2f3fd3a543e5

    Login or Signup to reply.
  3. Try disabling pointer events on the child:

    <button ...>
      <span className="icon">
         <i className="..."></i>
      </span>
    </button>
    

    in the css file:

    .icon {
        pointer-events: none;
    }
    
    Login or Signup to reply.
  4. Please use currentTarget

    const App = () => {    
        const toggle = (event) => {
            const id = event.currentTarget.value;
            console.log(id);
        };
    
        return (
            <div>
                <button value="test val" onClick={toggle}>TEST</button>
            </div>
        )
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
    <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
    <div id="root"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search