What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the component's state or functions. Can someone help me figure out what I am doing wrong?

import React, { useState } from "react";
import ReactDOM from 'react-dom';
//import { DataGrid } from '@material-ui/data-grid';
import { XGrid } from '@material-ui/x-grid';
import "regenerator-runtime/runtime";

function filterModelChanged()
{
    console.log(this.getSortModel());
    console.log(this.state.filter.items);
}

function ReaderWorklist({ initialRows, columns }) {
    const [rows, setRows] = useState(initialRows);

    return (
        <div style={{ height: 600, width: '100%' }}>
        <XGrid rows={rows} columns={columns} onFilterModelChange={filterModelChanged} ref={(xgridComponent) => {window.xgridComponent = xgridComponent}} />
            </div>
    );
}

//
async function getData() {
    let response = await fetch("/services/reader_worklist_services/getList",
                                {credentials:"same-origin"});
    return await response.text();
}

//Ensure all elements are present before attaching to them with the react component
document.addEventListener("DOMContentLoaded", function(event) {
    getData().then(function(data) {
        const rootElement = document.getElementById('reader_worklist_container');
        const jsData = JSON.parse(data);
        ReactDOM.render(<ReaderWorklist initialRows={jsData.rows} columns={jsData.columns} />, rootElement);
    });
});


Answer №1

Transfer the filterModelChanged function to reside within the ReaderWorkList component. In addition, define the getSortModel method within the same component and initialize the filter state. Considering that ReaderWorkList is a functional component, it's important to note that the use of this may not behave as expected and should be avoided.

You can structure it like so:

function ReaderWorklist({ initialRows, columns }) {
  const [rows, setRows] = useState(initialRows);
  const [filter, setFilter] = useState({
    items: [],
  });

  function getSortModel() {
    // implement functionality here
  }

  function filterModelChanged() {
    console.log(getSortModel());
    console.log(filter.items);
  }

  return (
    <div style={{ height: 600, width: '100%' }}>
      <XGrid
        rows={rows}
        columns={columns}
        onFilterModelChange={filterModelChanged}
        ref={(xgridComponent) => {
          window.xgridComponent = xgridComponent;
        }}
      />
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Kendo UI Web - MultiSelect: choosing an option multiple times

Currently, I am encountering an issue with the Kendo UI MultiSelect widget when trying to select an option multiple times. An example of this is shown in the image below where I want to choose Schindler's List again after selecting The Dark Knight. Ho ...

Managing CSRF tokens in React Relay: best practices

I have been diligently working on a React Native application that communicates with a GraphQL API from a Django server. Within React Native, I have decided to utilize React Relay for handling my GraphQL requests (following the instructions provided here). ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Transitioning to mui5's sx prop instead of makeStyles is generating a typescript error - none of the overloads match this call when passing an object with

I encountered an issue while converting a component to mui 5. Here is the original code snippet: const useStyles = makeStyles({ imageContainer: { display: "flex", width: "65%", float: "left", marginRight ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

Display requested tab feature using jQuery upon page load

I am new to jquery and have been using this code for creating tabs: <script type="text/javascript" charset="utf-8> $(function () { var tabContainers = $('div.tabs > div'); tabContainers.hide().filter(':first&apo ...

Automatically fill in a text box with previously saved information

Does anyone have suggestions on how to create this type of textbox or what it is called? (View original image here) ...

When using Owl Carousel in Chrome, the carousel unexpectedly stops after switching tabs

Hi there, I'm currently testing out the auto play feature in owl carousel. One issue I've encountered is that when I switch to another tab in Chrome and then return to my webpage with the carousel, it stops functioning unless I manually drag the ...

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...

Align audio and video elements in HTML5 using JavaScript

I am facing a situation where I have two files - one is a video file without volume and the other is an audio file. I am trying to play both of these files using <audio> and <video> tags. My goal is to make sure that both files are ready to pla ...

Looking for insights on reading and presenting XML files from a URL? Learn how to achieve this effortlessly with the power

Currently, I'm in the process of developing an innovative Android application using PhoneGap. My main objective is to dynamically present the data stored within a customized XML file hosted on my website that follows the .php format. Do you happen to ...

Highcharts - resolving cross-browser e.Offset discrepancies in mouse event detection on charts

I need to determine if the mouseup event is inside the chart and display the coordinates of the point. The code works in Chrome but not in Firefox due to the lack of the event.offset property. jQuery(chart.container).mouseup(function (event) { eoff ...

Error message: "When using REACTJS.NET server-side rendering, an issue arises where the object does not have support for the 'forwardRef'

Looking to implement server-side rendering for my REACT components using REACTJS.NET within an ASP.NET project. In the SSR JavaScript file, I am including the SimpleBar component from the simplebar-react package, which is triggering the error message Type ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value betw ...

Guide to implementing onhashchange with dynamic elements

Hey there! I've encountered a problem with two select boxes on my webpage, each in different anchors (one on the page, the other in an iframe). What I'm trying to achieve is for the code to recognize which anchor it's in and then pass the se ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

Error property for text field validation in Material UI allows for easy checking and validation of

In my React UI app, I am implementing an error property to highlight a text box in red when it exceeds the maximum character limit. The logic for this is based on https://mui.com/components/text-fields/#validation Currently, the red color only appears whe ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...