Sunday, June 19, 2022

How to use React createRef in material Table

React provides a feature known just as refs that object over there allow for dom access from components. The reader attaches a ref to an element in an object belonging to you, that object being your application to provide access to the element’s dom from anywhere within an object belonging to you, that object being your component.

Refs currently are able to also exists used to provide direct access to react elements in addition to not just dom nodes. Here now lives whatever the react documentation says concerning refs:

create ref



Creating refs in React
React provides three major ways of creating refs. Here currently exists a list of the different methods starting from the oldest of them:
  1. String refs (legacy method)
  2. Callback refs
  3. createRef Hook
  4. The useRef Hook 

String refs in React
The legacy way of creating refs in a react application currently exists using string refs. This object over here currently exists as the oldest method in addition to currently existing considered legacy or deprecated owing to the fact that it will exist removed in future releases of react.

String refs currently are simply created by adding a ref prop to the desired element, passing a string name for the ref just as its value. Here currently exists a simple example:

HTML:
 <input type="text" ref="inputField" />

 

JS:
 const value = this.refs.inputField.value;

 

we can update this value using Java Script:
this.refs.inputField.value =
      isUpper
        ? value.toLowerCase()
        : value.toUpperCase();

Using callback refs in React

Callback refs use a callback function for creating refs instead of passing the name of the ref just as a string. If the reader currently are using versions of react earlier than version 16.3, then this object over here should exist an object belonging to you, that object being your preferred method of creating refs.

The callback function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. Using a callback ref, our previous code snippet will become the following.

HTML:
 <input type="text" ref={elem => this.inputField = elem} />

JS:
 const value = this.refs.inputField.value;
we can update this value using Java Script:
this.refs.inputField.value =
      isUpper
        ? value.toLowerCase()

Here we have made two major changes. First we defined the ref using a callback function and storing it in this.inputField as follows:

<input type="text" ref={elem => this.inputField = elem} />

Then, in the event handler, we access the ref using this.inputField instead of this.refs.inputField.

Callback refs use a callback function for creating refs instead of passing the name of the ref as a string. If you are using versions of React earlier than version 16.3, then this should be your preferred method of creating refs.

Using the React useRef Hook

With its release in react v16, the hooks api has become the de facto means of abstracting in addition to reusing code in react applications. One such hook currently exists useref, which allows us to create in addition to use refs in functional components.

Note that object over there even with the useref hook the reader still, by default, cannot use the ref attribute on functional components owing to the fact that all of us cannot create instances of functions. All of us will discuss how to get around this object over here with ref forwarding later on in this object over here article.

Note that even with the useRef Hook you still, by default, cannot use the ref attribute on functional components because we cannot create instances of functions. We will discuss how to get around this with ref forwarding later on in this article.

Using React.createRef

Starting from react 16.3, the react api included a createref() method that object over there currently am able to exists used for creating refs in much the same way just as all of us did using the callback function. The reader simply create a ref by calling react.createref() in addition to assign the resulting ref to an element.

Now we discuss Topic createRef with meterial Table createRef

1. How to import:

import { createRef, useEffect, useState } from "react"; //import
...
const tableRef = createRef();  //call and store in a variable

How to implement


2. How to attach with meterial table:

 <MaterialTable
        ref={ref}
        icons={tableIcons}
        tableRef={ref}
        title={props.title}
        columns={props.columns}
        data={props.data}
        options={props.options}
        onSearchChange={(ele) => {
          console.log("In table : ", ele);
        }}
      />

Material table


3. How to get value from ref object:

let localData = type === "all" ? completeData : ref.current.state.data;
 
4. How to implement global search in table:

 const handleUpdate = (type) => {
    console.log(ref.current.state.data);
    console.log(type, { completeData });
    let localData = type === "all" ? completeData : ref.current.state.data;
    setTableData(
      localData.filter((ele) => {
        return (
          `${ele.id}`.toLowerCase().includes(value.toLowerCase()) ||
          `${ele.first_name}`.toLowerCase().includes(value.toLowerCase()) ||
          `${ele.gender}`.toLowerCase().includes(value.toLowerCase()) ||
          `${ele.last_name}`.toLowerCase().includes(value.toLowerCase()) ||
          `${ele.shares}`.toLowerCase().includes(value.toLowerCase()) ||
          `${ele.ip_address}`.toLowerCase().includes(value.toLowerCase())
        );
      })
    );
    setAnchorEl(null);
    setValue("");
  };

5. How to download CSV file of table data:

 const handleDownload = (type) => {
    let localData = type === "all" ? completeData : ref.current.state.data;
    console.log(localData);
    let newData = localData.map((ele) => {
      return `${ele.id},${ele.first_name},${ele.last_name},${ele.email},${ele.gender},
${ele.ip_address},${ele.shares}`;
    });
    let finalData = [
      `"Member ID","First Name","Last Name","Member Email","Member Gender",
"Member ip_address","Shares"`,
      ...newData,
    ].join("\n");
    let hiddenElement = document.createElement("a");
    hiddenElement.href =
      "data:text/csv;charset=utf-8," + encodeURIComponent(finalData);
    hiddenElement.target = "_blank";
    hiddenElement.download = `ss_${type}_data.csv`;
    hiddenElement.click();
}; 



No comments:

Post a Comment

Thanks

Climate Crisis and Innovation: Navigating Earth's Future

Climate Change: Recent Events and Technological Solutions 1. The Escalating Climate Crisis The climate crisis has intensified in recent year...