Ad
How To Create A Ref Using Typescript And Styled-components
I'm trying to add a ref to React component like this:
const Dashboard: React.FC = () => {
const [headerHeight, setHeaderHeight] = useState(0);
const headerRef = React.createRef<HTMLInputElement>();
useEffect(() => {
// @ts-ignore: Object is possibly 'null'
setHeaderHeight(ref.current.clientHeight)
});
return (
<Root>
<Header ref={headerRef} />
<div>other contents</div>
</Root>
);
};
<Header />
is a simple React.FC
.
TS gives an error saying:
Type '{ ref: RefObject; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'
How can I overcome this issue?
Ad
Answer
Looks like you're trying to give a ref typed for an input element to another React component. If you are trying to forward the ref to an element inside the Header
component, you can use React's forwardRef function.
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad