Reputation: 1518
I have a component where i am passing the ref value. I need to get the passed ref value in Higher Order component. Here is the code example: Component wrapped with HOC:
import React from "react";
import HOC from './hoc';
const MeasuredInput = () => {
const ref = React.createRef();
return (
<div>
<button ref={ref}>Click me!</button>
</div>
)
};
export default HOC(MeasuredInput);
Higher Order Component:
import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
function NewComponent(props) {
const { forwardedRef } = props;
return <OriginalComponent ref={forwardedRef} {...props} />;
}
return React.forwardRef((props, ref) => {
return <NewComponent {...props} forwardedRef={ref} />;
});
};
Thanks in Advance
Upvotes: 1
Views: 622
Reputation: 19214
You would need to create the ref
in the HOC and pass it down, not the other way around. Data flows down and HOC is wrapping the component.
import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
return function(props) {
const ref = useRef();
return <OriginalComponent ref={ref} {...props} />
}
};
Original Component:
import React from "react";
import HOC from './hoc';
const MeasuredInput = React.forwardRef((props, ref) => {
return (
<div>
<button ref={ref}>Click me!</button>
</div>
)
});
export default HOC(MeasuredInput);
Upvotes: 1