React Re render issue from Child to parent Component

54 views Asked by At

i have created a separate file for table id copy to clipboard and tooltip, i am facing issue when hovering the icon when i copied more than one the previous one is not changing to default in this order id first i copied if i click second id it should change copied and first back to copy tooltip . parent component is not rendering the one

i have multiple list component each components consist of table's each table has id's for that if i used locally state and onclick function it working fine no problem if i have two or three id's i want declare separate state and click function so that i have create separate component as child for common use for whole project if i declare the states and onclick function in parent then no use of child component Right

Parent Component Table Array.map

<td>
<CopyID copyText={list?.orderId} rowIndex={i}/> 
</td>                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Child Component

import { Tooltip } from 'antd';
import React, { useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
export const CopyID = ({copyText,rowIndex}) => {
const [triggeredIndex, setTriggeredIndex] = useState(null);
const orderIdCopy = (i) => {
    setTriggeredIndex(i);
};


return (
    <CopyToClipboard text={copyText || ' '} onCopy={() => orderIdCopy(rowIndex)}>
        <Tooltip
            overlayClassName='custom-tooltip-style'
            title={triggeredIndex === rowIndex ? 'Copied' : 'Copy'}
            color={triggeredIndex === rowIndex ? '#018c5c' : 'geekblue'}>
            <i
              key={rowIndex}
                className='bx bx-copy me-2 align-middle fs-6 '
                style={{
                    cursor: 'pointer'
                }}></i>
        </Tooltip>
    </CopyToClipboard>
);
};
1

There are 1 answers

2
Akalanka Dissanayake On

The issue you're facing arises because each CopyID component maintains its own triggeredIndex state, which tracks whether its tooltip should display "Copied" or "Copy".

To solve this, you need a way to globally track the last copied ID across all CopyID components.

const ParentComponent = ({ dataList }) => {
  const [lastCopiedIndex, setLastCopiedIndex] = useState(null);

  const handleCopy = (index) => {
    setLastCopiedIndex(index);
  };
}

Child

export const CopyID = ({ copyText, rowIndex, onCopy, isLastCopied }) => {}

State should handled like this.