1

I have a button that I need the background color and inner text to on click. I tried the document.getElementById method but it is not applying the changes. How to I solve this issue?

<TableBody>
    {
        records === null ?
        []
        :
        records.map((item, index) => (
            <button className="addToggle" id={"addToggle" + index} onClick={() => handleAddSwitch(item, index)}>
                <CircleCheckIcon />
                Add
            </button>
        ))
    }
</TableBody>


function handleAddSwitch(item, index) {
    document.getElementById("addToggle" + index).style.backgroundColor = "red";
    document.getElementById("addToggle" + index).innerHTML= "Added";
}
3
  • I have tried creating sample. It works fine: codesandbox.io/s/stupefied-resonance-mqw3m Try checking what is the value ofitem,index in handleAddSwitch Commented Oct 14, 2021 at 11:57
  • What is the problem now? Commented Oct 14, 2021 at 11:58
  • @ShubhamVerma I logged the values and they are correct Commented Oct 14, 2021 at 12:01

1 Answer 1

2

You can use event.target OR event.currentTarget:

<button className="addToggle" id={"addToggle" + index} onClick={(e) => handleAddSwitch(e, index)}>
    <CircleCheckIcon />
    Add
</button>

Function

const handleAddSwitch(e, index) => {
    e.target.style.backgroundColor = "red";
    e.target.innerHTML= "Added";
}
Sign up to request clarification or add additional context in comments.

5 Comments

it worked but it deleted the icon <CircleCheckIcon />, how do I solve this?
insert Add to span element then: e.target.children[1].innerHTML = "...";
e.target.children[1] is undefined
at the first, append Add to span, then Log it: e.target.children
@Nour If it works, please confirm it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.