Search code examples
reactjsbuttondisable

How to disable button after one click in React.js


I want to disable button after one click. I use this code:

const handleClick = (event) => {
    event.currentTarget.disabled = true;
    console.log(event);
    console.log('button clicked');
  };

When I have only one button it Works.

<div className="col-md-1">
          <button type="submit" onClick={handleClick} className="btn btn- 
                success">Filtriraj</button>
        </div>

but when I have multiple same buttons it doesn't work.

<div className="showAds" >
        {adsList.map((val, key) => {
          return <div className="ad" key={key}>
            <h4> {val.content}</h4>
            <h5><a href=""><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#bb2d3b" className="bi bi-geo-alt-fill" viewBox="0 0 16 16">
              <path d="M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10zm0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"></path>
            </svg>{val.adress}</a></h5>
            <h5>Likes: {val.likes}</h5>
            <div>
              {""}
              <button type="submit" onClick={() => {addLike(val.id, val.likes + 1);handleClick}} className="btn btn-success" > LIKE</button>
            </div>
          </div>
        })}
      </div>

The problem is when I try to call handleClick it shows me the error:

 Expected an assignment or function call and instead saw an expression

Solution

  • In your click handler you have

    () => {addLike(val.id, val.likes + 1);handleClick}
    

    This ignores the event argument, also it incorrectly calls the handleClick. A correct version would be

    (e) => {addLike(val.id, val.likes + 1);handleClick(e)}
    

    This takes the argument of the event (e) and passes it to handleClick.