Skip to content

Instantly share code, notes, and snippets.

@ChrisDobby
Created July 30, 2019 20:03
Show Gist options
  • Save ChrisDobby/de57c0e1c103780c41232a0ed29c7f2f to your computer and use it in GitHub Desktop.
Save ChrisDobby/de57c0e1c103780c41232a0ed29c7f2f to your computer and use it in GitHub Desktop.
Example of React component in Typescript using forwarding refs
import * as React from "react";
const Forward = React.forwardRef((props, ref: React.Ref<HTMLDivElement>) => (
<div ref={ref} style={{ width: "100%", height: "30px", backgroundColor: "green" }} />
));
function ForwardRef() {
const divRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
if (divRef.current) {
console.log(`forwardRefRef div width: ${divRef.current.clientWidth}`);
}
});
return <Forward ref={divRef} />;
}
export default ForwardRef;
@cmmartin
Copy link

cmmartin commented Jun 2, 2021

This complains when I then try to access the ref within the Forward component body. Forward is passed a RefObject but any reference to ref.current makes TS complain :(

@giannif
Copy link

giannif commented Jun 9, 2021

@cmmartin did you figure this out?

@giannif
Copy link

giannif commented Jun 9, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment