forwardRef
Call forwardRef() to let your component receive a ref and forward it to a child component.
import { forwardRef } from 'react'
const MyInput = forwardRef( function MyInput(props, ref) {
return (
<label>
{props.label}
<input ref={ref} />
</label>
)
}
)
Note: In Strict mode will call your render function twice to make sure it does not affect production.
----------------
forwardRef( renderFunction, ref )
Parameters
-
props
: The props passed by the parent component. -
ref
: Theref
attribute passed by the parent component. Theref
can be an object or a function. If the parent component has not passed a ref, it will benull
. You should either pass theref
you receive to another component, or pass it touseImperativeHandle
.
Returns
forwardRef
returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by forwardRef
is able to take a ref
prop.
--------------
function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
}
return (
<form>
<MyInput label="Enter your name:" ref={ref} />
<button type="button" onClick={handleClick}>
Edit
</button>
</form>
);
}
----------------
// App.js
import { useRef } from 'react';
import MyVideoPlayer from './MyVideoPlayer.js';
export default function App() {
const ref = useRef(null);
return (
<>
<button onClick={() => ref.current.play()}>
Play
</button>
<button onClick={() => ref.current.pause()}>
Pause
</button>
<br />
<MyVideoPlayer
ref={ref}
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
type="video/mp4"
width="250"
/>
</>
);
}
import { forwardRef } from 'react';
const VideoPlayer = forwardRef(function VideoPlayer({ src, type, width }, ref) {
return (
<video width={width} ref={ref}>
<source
src={src}
type={type}
/>
</video>
);
});
export default VideoPlayer;