I'm implementing a link in React and TypesSript that, after clicking, scrolls to the right ponent, I'm using useRef Hook.
But when I do that, the error occurs:
Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assignable to type 'IntrinsicAttributes'.
Property 'ref' does not exist on type 'IntrinsicAttributes'.
Below is the code, what am I doing wrong? I've tried several ways.
import NewComponent from '../NewComponent';
const titleRef = useRef<null | HTMLDivElement>(null);
const handleBackClick = (): any => {
titleRef!.current!.scrollIntoView({ behavior: 'smooth' });
};
return (
<Container>
<Link onClick={handleBackClick}>
Button Text
</Link>
...
...
...
<SomeComponents />
...
...
...
...
<NewComponent ref={titleRef} />
</Container>
)
The NewComponent
is a simple ponent, like:
const NewComponent = () => {
return (
<Container>
// Its a simple ponent
</Container>
);
};
export default NewComponent;
Thanks to anyone who can help me with this!
I'm implementing a link in React and TypesSript that, after clicking, scrolls to the right ponent, I'm using useRef Hook.
But when I do that, the error occurs:
Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assignable to type 'IntrinsicAttributes'.
Property 'ref' does not exist on type 'IntrinsicAttributes'.
Below is the code, what am I doing wrong? I've tried several ways.
import NewComponent from '../NewComponent';
const titleRef = useRef<null | HTMLDivElement>(null);
const handleBackClick = (): any => {
titleRef!.current!.scrollIntoView({ behavior: 'smooth' });
};
return (
<Container>
<Link onClick={handleBackClick}>
Button Text
</Link>
...
...
...
<SomeComponents />
...
...
...
...
<NewComponent ref={titleRef} />
</Container>
)
The NewComponent
is a simple ponent, like:
const NewComponent = () => {
return (
<Container>
// Its a simple ponent
</Container>
);
};
export default NewComponent;
Thanks to anyone who can help me with this!
Share Improve this question edited Mar 19, 2023 at 12:01 Youssouf Oumar 46.6k16 gold badges103 silver badges105 bronze badges asked Aug 8, 2022 at 13:06 gmcodegmcode 1032 silver badges12 bronze badges 02 Answers
Reset to default 5You would wanna use forwardRef
to tell TypeScript that NewComponent
can accept a ref
that will hold a div
element. Here is how you would do it as an example:
import { forwardRef, ReactNode } from "react";
interface Props {
children: ReactNode;
}
const NewComponent = forwardRef<HTMLDivElement, Props>((props, ref) => {
return <div ref={ref}>{props.children}</div>;
});
export default NewComponent;
import { useRef } from "react";
import NewComponent from "./NewComponent";
export default function App() {
const titleRef = useRef<HTMLDivElement>(null);
return <NewComponent ref={titleRef}>Some content</NewComponent>;
}
In React, ref
can only attach to DOM, if you want to pass it to your react ponent, you should use forwardRef
you can find more detail here https://reactjs/docs/react-api.html#reactforwardref