Passing Reference to props not working

Hi, i want to ask something. so i have component called ParentComponent. then i defined a refrence let grid: Grid | null. and the i passed it to Table Component and ColumnAction Component. in parent component there is function called hide with method hideColumns, then i put on button. it's doesn't work, meanwhile the same function & button inside Table, it'working. can you tell me what's wrong in my code? Thank you

const ParentComponent = () => {
const [openFilterAction, setOpenFilterAction] = useState<boolean>(false);
const [openColumnAction, setOpenColumnAction] = useState<boolean>(true);
const [tableData, setTableData] = useState<TableData[]>(tableColumns);
let grid: Grid | null;

const handleColumnToggle = (updatedTableData: TableData[]) => {
setTableData(updatedTableData);
};

const hide = () => {
if (grid) {
grid.hideColumns("tahunPajak", "field");
}
};

return (
<Box pt="18px">
<Button onClick={hide}>Hide</Button>
<ColumnAction
open={openColumnAction}
onClose={() => setOpenColumnAction(false)}
tableData={tableData}
onColumnToggle={handleColumnToggle}
refGrid={grid}
/>
<Table data={data} columns={tableData} refGrid={grid} />
</Box>
);
};

export default ParentComponent;

======================================


interface TableProps {
data: any[];
columns: ColumnConfig[];
pageSizeOptions?: number[];
refGrid: any;
}
const Table: React.FC<TableProps> = ({
data,
columns,
pageSizeOptions = [5, 10, 20, 30, 50],
refGrid,
}) => {
const [pageSize, setPageSize] = useState(pageSizeOptions[0].toString());
const [currentPage, setCurrentPage] = useState("1");
const [totalPages, setTotalPages] = useState("1");
const [pagedData, setPagedData] = useState<any[]>([]);
const [selectedRows, setSelectedRows] = useState<any[]>([]);


const hide = () => {
if (refGrid) {
refGrid.hideColumns("tahunPajak", "field");
}
};

return (
<>
{selectedRows.length > 0 && (
<ActionBar
selectedIndex={selectedRows.length}
handleDeselectAll={handleDeselectAll}
/>
)}

<GridComponent
dataSource={pagedData}
enableStickyHeader
height="100%"
width="100%"
frozenColumns={3}
allowTextWrap
textWrapSettings={{ wrapMode: "Header" }}
selectionSettings={{
checkboxOnly: true,
type: "Multiple",
}}
rowSelected={handleRowSelected}
rowDeselected={handleRowDeselected}
ref={(g) => (refGrid = g)}
autoFit
>
<ColumnsDirective>
<ColumnDirective type="checkbox" width={40} />
{columns.map((column, index) => (
<ColumnDirective
key={index}
field={column.field}
headerText={column.headerText}
width={column.width}
template={column.template}
freeze={column.freeze}
visible={column.isVisible}
autoFit
/>
))}
</ColumnsDirective>
<Inject services={[Edit, CommandColumn, Page, Freeze, Resize]} />
</GridComponent>

<Button onClick={hide}>Hide</Button>

<Stack flexDirection="row" justifyContent="space-between" mt="14px">
<Stack flexDirection="row" alignItems="center" gap="8px">
<Typography
sx={{
fontSize: "14px",
lineHeight: "20px",
fontWeight: 400,
color: "#212529",
}}
>
Baris per halaman
</Typography>
<Select
value={pageSize}
onChange={(e) => {
setCurrentPage("1");
setPageSize(e.target.value);
}}
fullWidth
sx={{
width: "72px",
height: "40px",
backgroundColor: "#ffffff",
}}
>
{pageSizeOptions.map((size) => (
<MenuItem key={size} value={size.toString()}>
{size}
</MenuItem>
))}
</Select>
</Stack>

<Stack flexDirection="row" alignItems="center">
<Stack flexDirection="row" alignItems="center" gap="8px">
<Box>
<Select
value={currentPage}
onChange={(e) => onPageChange(parseInt(e.target.value, 10))}
fullWidth
sx={{
width: "72px",
height: "40px",
backgroundColor: "#ffffff",
}}
>
{Array.from({ length: parseInt(totalPages, 10) }, (_, i) => (
<MenuItem key={i + 1} value={(i + 1).toString()}>
{i + 1}
</MenuItem>
))}
</Select>
</Box>
<Typography
sx={{
fontSize: "14px",
fontWeight: 400,
lineHeight: "20px",
color: "#212529",
}}
>
dari {totalPages} Halaman
</Typography>
</Stack>

<Pagination
count={parseInt(totalPages, 10)}
page={parseInt(currentPage, 10)}
onChange={(_, page) => onPageChange(page)}
color="primary"
size="small"
/>
</Stack>
</Stack>
</>
);
};

export default Table;



1 Reply

AR Aishwarya Rameshbabu Syncfusion Team May 21, 2024 12:10 PM UTC

Hi Muhammad,


Greetings from Syncfusion support.


Upon reviewing your query, it appears that you are experiencing an issue with the hide method not properly hiding columns in the Grid component within the ParentComponent. After analyzing the shared code example, it seems that the problem may be due to the Grid reference not being defined correctly. Therefore, we recommend using the "useRef" hook to define the Grid reference. Please refer the below sample and the code example where we initialized the Grid instance with a useRef hook. Now the hide method is working properly with both ParentComponent and the Table Component.


Index.js

 

function ParentComponent() {

    const grid = useRef(null); // Creating a reference by initializing it with useRef as null.

    const hide = () => {

        // Accessing the grid instance using grid.current.

        if (grid.current) {

            grid.current.hideColumns('OrderID''field');

        }

    };

    return (

        <div className='control-pane'>

            <div className='control-section'>

                <h2>Parent Component</h2>

                <button onClick={hideColumn}>Hide OrderID Column</button>

            </div>

            <div className='control-section'>

                <h2>Child Component</h2>

                <Table refGrid={grid} />

            </div>

        </div>

    );

}

 

 

function Table({ refGrid }) {

    const hide = () => {  

        if (refGrid) {

            refGrid.current.hideColumns('OrderID''field'); 

        }

    };

    return (

        <div className='control-pane'>

              <button onClick={hideColumn}>Hide OrderID Column</button>

            <div className='control-section'>

                <GridComponent ref={refGrid} dataSource={data} allowPaging={true} pageSettings={pageCount: 5 }} allowSorting={true}>

                    <ColumnsDirective>

                        <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign='Right' />

                        <ColumnDirective field='CustomerName' headerText='Customer Name' width='150' />

                        <ColumnDirective field='OrderDate' headerText='Order Date' width='130' format='yMd' textAlign='Right' />

                        <ColumnDirective field='Freight' headerText='Freight' width='120' format='C2' textAlign='Right' />

                        <ColumnDirective field='ShippedDate' headerText='Shipped Date' width='130' format='yMd' textAlign='Right' />

                        <ColumnDirective field='ShipCountry' headerText='Ship Country' width='150' />

                    </ColumnsDirective>

                    <Inject services={[PageSort]} />

                </GridComponent>

            </div>

        </div>

 

    );

}

 


Sample: https://stackblitz.com/edit/react-egkytk-qeci3y?file=index.js,index.html


If you are still experiencing an issue, Please try to replicate it in the provided sample.


Regards

Aishwarya R


Loader.
Up arrow icon