I have an array of objects showing them in a table and one of the objects in this array is something that I want to copy to clipboard which has a copy icon button next to it but when i set the copy function it copies all the other objects in the array and I do not know how to detect which index has been clicked for copy!
const data = [
{title: "first", number: 1234},
{title: "second", number: 5678},
]
const [copied, setCopied] = useState(false);
const handleCopy = () => {
setCopied(data.map((item) => item.number));
navigator.clipboard.writeText(data.map((item) => item.number));
toast({
position: "top",
isclosable: true,
duration: 1500,
render: () => <BaseAlert title="number copied!" />,
});
setTimeout(() => {
setCopied("");
}, 3000);
};
<button onClick={handleCopy}>Copy</button>
When I click on the Copy button it copies two numbers in the array output: 1234, 5678 while i want to detect which button has been clicked to copy 1234 OR 5678!
send the array index to the handleCopy
function, then get that number from data
array like this:
const handleCopy = (index) => {
setCopied(data[index].number);
navigator.clipboard.writeText(data[index].number);
// ...rest
};