i am trying to build a custom component video player with react and mobx, and i need to drill a refrence from a main component to a child Component but i'm getting an error message when i use the forwardRef function on a component that is an observer. the error message is "baseComponent is not a function" Here's the code:
// code for main component
const videoPlayer = () => {
const controlsRef = useRef<any>(null);
return (<div>
// video player screen code //
<VideoPlayerButtonCode ref={controlsRef} />
<div>)
}
// the code for the players component
interface IProps{
controlsRef: any;
}
const VideoPlayerButtonCode: React.FC<IProps> = fowardRef({props from iprops}, controlsRef ) => {
return (<div>
<Button ref={controlsRef}>Button i want to get a ref for from main</Button>
<div>)
}
export default observer(VideoPlayerButtonCode)
thats a vague abstraction of the code but the same implementation. is there any help for mobx supports for ref or is there a way i can store the refrence in a mobx store?
What version of mobx-react
are you using? It should work fine with latest 7.0.0 version, but it seems to fail if you are using mobx-react-lite@3.0.0
.
I've made codesandbox with all working variants as for now: https://codesandbox.io/s/httpsstackoverflowcomquestions64227496-75xdz?file=/src/App.js
For example same version as your works fine:
const ComponentWithForwardRef = React.forwardRef((props, ref) => {
return <div ref={ref}>My Observer Component</div>;
});
const ObserverComponentWithForwardRef = observer(ComponentWithForwardRef);
There is also a forwardRef
option for observer
HOC, but it only currently works with mobx-react-lite
, and does not work with regular mobx-react
package due to this bug https://github.com/mobxjs/mobx-react/issues/868
You can use it like that:
const MyObserverComponent = observer(
(props, ref) => {
return <div ref={ref}>My Observer Component</div>;
},
{ forwardRef: true }
);
If everything fails you can just use custom prop for your ref like so:
<MyObserverComponentCustomRef innerRef={myRef} />
// ...
const MyObserverComponentCustomRef = observer((props) => {
return <div ref={props.innerRef}>My Observer Component Inner Ref</div>;
});