I have an example I have created in codepen. The table renders with th, but within my IDE the typescript complains about the type at this line:
<TH handleSort={handleSort} ref={refsTh[ind]}>
--- Error Type 'MutableRefObject' is not assignable to type '((instance: HTMLTableHeaderCellElement | null) => void) | RefObject | null | undefined'. Type 'MutableRefObject' is not assignable to type 'RefObject'. Types of property 'current' are incompatible. Type 'unknown' is not assignable to type 'HTMLTableHeaderCellElement | null'. Type 'unknown' is not assignable to type 'HTMLTableHeaderCellElement'.
I have made this example work when not passing an array and instead a single ref. The problem seems to be because I am creating useRefs dynamically inside an array. Can anyone please advise? Thanks
example code: https://codepen.io/inspiraller/pen/OJMRZWQ
// import React from 'react';
// ######################################
type shapeTH = {
handleSort: () => void,
children: React.ReactNode // BUG: can't pass children any other way to forwardRef
};
type Ref = HTMLTableHeaderCellElement | null;
const TH = React.forwardRef<Ref, shapeTH>(
({children, handleSort}, ref) => (
<th ref={ref} onClick={handleSort}>
<span className="thSpan">{children}</span>
</th>
)
);
// const TH:React.FC<shapeTH> = ({children, handleSort}) => (
// <th onClick={handleSort}>
// <span className="thSpan">{children}</span>
// </th>
// );
// ##################################################
const App:React.FC = () => {
const arrTh=['id', 'name', 'colour'];
type shapeRef = ReturnType<typeof React.useRef>;
const refsTh: Array<shapeRef> = arrTh.map(() => (
React.useRef<HTMLTableHeaderCellElement>(null)
));
const handleSort: shapeTH['handleSort'] = () => {};
return (
<table className="tableGeneric">
<thead>
<tr>
{
arrTh.map((item, ind) => (
<TH handleSort={handleSort} ref={refsTh[ind]}>
{item}
</TH>
))
}
</tr>
</thead>
</table>
);
};
// export default App;
ReactDOM.render(
<App/>,
document.getElementById('app')
);