Using a forwardRef to Create External Controls

InstructorLindsey Kopacz

Share this video with your friends

Send Tweet

React's forwardRef function allows a component to receive a ref that has been created outside of it. This can be useful in cases where you want to have a specific part of your component, such as a section of a long transcript or a specific part of an audio recording, referenced from outside the component.

One example of when this might be useful is if you have a "listicle" type of audio, such as "5 things your tech resume needs", and you want to allow users to jump to specific parts of the audio. By converting the component to a forwarded ref component, you can create a ref in the parent component (in this case, the "App" component) and pass it into the audio component. This allows you to create a few buttons in the parent component that can control the audio ref and jump to specific audio sections.

To convert a component to a forwarded ref component, you can use React's forwardRef function to wrap the component, and then remove the audio ref and replace all instances with the new ref.

By doing this, you can now control the audio component, like play, pause and jump to a specific time, by interacting with the audioRef ref object created in the parent component and passed into the audio component.

Think about: What ways to control the audio outside the component could help with accessibility?