At React Typesciprt Web App, how to define the type of useRef to get Handsontable instance?

Tags: #<Tag:0x00007efc61a2c1a0>

Hello

Currently, I am working on React Typescript Web App.

import { useRef, useEffect } from "react";
import { HotTable } from "@handsontable/react";
import Handsontable from "handsontable";

const hotSettings = {
  data: Handsontable.helper.createSpreadsheetData(4, 4),
  colHeaders: true,
  height: "auto",
  licenseKey: "non-commercial-and-evaluation",
};

export const About = () => {
  const hotTableComponent = useRef(null);
  const swapHotData = () => {
    hotTableComponent.current.hotInstance.loadData([["new", "data"]]);
  };

  useEffect(() => {
    hotTableComponent.current.hotInstance.loadData([["new", "data"]]);
  }, []);

  return (
    <div className="controls">
      <HotTable ref={hotTableComponent} settings={hotSettings} />
      <br />
      <button onClick={swapHotData}>Load new data!</button>
    </div>
  );
};

on there, I got the following error.

Regards

Hi @forevereffort

I recreated your issue in jsfiddle and locally on React + TypeScript project and in both cases I didn’t get any errors.

https://jsfiddle.net/aszymanski/6k3p75e4/34/

@forevereffort It’s because you initialize the ref as:
const hotTableComponent = useRef(null);

This means that hotTableComponent could be null and so getting the “current” property of null will result in an error.

One way to get around this is to use the optional chaining operator:
hotTableComponent?.current?.hotInstance.loadData( [ … ])

Hi @niconal902

I’m not sure about the status of this topic. Could you please tell me if the topic can be closed or you still need feedback?

Hi @aleksandra_budnik, I was just responding to @forevereffort to help with their problem. It seems to be resolved.

Thank you for the update @niconal902
I think that if we do not have updates since @forevereffort posted the question in February we can close the topic.