How can I access the ref of elements? Can I just pass ref
to the props to access them?
Yes, Matthias. By default, components exported by Plasmic already export a ref
prop that can be used to access their root element. And if you want to access an internal element, you can pass a ref like <Component subElement={{ref}} />
to clarify (because I struggled with this for a while)
When you want to use the ref inside “Component” it needs to be passed a ref from its parent.
Am I right @tiago?
for me the ref prop passed down and referencing the component you’re in was null otherwise
something regarding refs, that I don’t understand:
why is every component wrapped as a forward ref, like this:
const VideoItem = React.forwardRef(VideoItem_);
export default VideoItem;
forwardRef
is how you can enable your custom components take in a ref
prop, just like native DOM elements like <div/>
etc. So basically, you can do:
const videoRef = React.useRef<HTMLDivElement>(null);
<VideoItem ref={videoRef} />
By default, this will get you the ref to the root element.
This is for passing refs to your wrapper component. But inside your wrapper component, you may also want refs to various pieces of your component elements. You can do so by passing in refs as overrides:
function VideoItem_(props, ref) {
const playButtonRef = React.useRef<HTMLButtonElement>(null);
return (
<PlasmicVideoItem
// pass on the forwarded ref
root={{ref}}
// get ref to some sub element
playButton={{ref: playButtonRef}}
/>
);
}
const VideoItem = React.forwardRef(VideoItem_);
Sometimes, you may find that you also need access to the root ref within your wrapper component. The usual way to deal with this is with something like https://github.com/gregberge/react-merge-refs
import mergeRefs from "react-merge-refs";
function VideoItem_(props, ref) {
const rootRef = React.useRef<HTMLDivElement>(null);
const playButtonRef = React.useRef<HTMLButtonElement>(null);
return (
<PlasmicVideoItem
// pass in both the ref to forward, and the rootRef that you need to use
// within the wrapper component
root={{ref: mergeRefs([localRef, ref])}}
/>
);
}
const VideoItem = React.forwardRef(VideoItem_);
great!