0
votes

This code validates under typescript:

type Ref = HTMLTableElement;

const Table = forwardRef<Ref, shapeTable>(({filtered, handleSort, paginationOptions, summary, onMount}, refTable) => {

  useEffect(() => {
    if(refTable && typeof refTable !== 'function' && refTable.current) {
      const tableWidth:string = window.getComputedStyle(refTable.current).getPropertyValue("width");
      onMount(tableWidth);
    }
  }, [refTable, onMount]);

This code does not validate under typescript:

When I put the type refTable inside an object as below, and I update the Ref type to allow for that, it does not validate. How can I fix this? I need to be able to pass more than one ref into forwardRef. I have done this previously without using typescript and it works. So something about forwardRef seems to insist only one ref type can pass. Unless its a simpler matter of updating my Ref type:

Type '((instance: Ref | null) => void) | MutableRefObject | null' is not assignable to type 'Ref'. Type 'null' is not assignable to type 'Ref'.

type Ref = {
  refTable: HTMLTableElement
};

const Table = forwardRef<Ref, shapeTable>(({filtered, handleSort, paginationOptions, summary, onMount}, ref) => {
  const {refTable}:Ref = ref;

  useEffect(() => {
    if(refTable && typeof refTable !== 'function' && refTable.current) {
      const tableWidth:string = window.getComputedStyle(refTable.current).getPropertyValue("width");
      onMount(tableWidth);
    }
  }, [refTable, onMount]);

1

1 Answers

0
votes

You are confused about which properties are on which objects. In the second example you have a ref to an object with a refTable property. If your ref is a ref object (not a callback ref) then it would look like:

ref = {
  current: {
    refTable: HTMLTableElement,
  }
}

So you need to look for current on the ref first and then look for refTable on ref.current.

Revised code:

const Table = forwardRef<Ref, shapeTable>(({ filtered, handleSort, paginationOptions, summary, onMount }, ref) => {

  useEffect(() => {
    if (ref && typeof ref !== 'function' && ref.current) {
      const table = ref.current.refTable;
      const tableWidth = window.getComputedStyle(table).getPropertyValue("width");
      onMount(tableWidth);
    }
  }, [ref, onMount]);
  
...

Typescript Playground Link

Be aware that using refs in useEffect dependencies is not recommended.