I am trying to use a useRef
between 2 components which are not directly linked.
How?
Since useRef is a hook, I cant just add this to some file and share it.
export const someRef = React.useRef(); // not possible, it needs to be inside a jsx component
I am trying to find a way to use it globally similar to how this would have been possible if this was state.
I’d have just used existing Redux
implementation or context
if this was state.
Please advice how to do the same for useRef
. I don’t own Compo2 component below thus I need to stick with a ref here.
P.S: I could achieve this with some prop drilling going 6 levels down.. Trying not to do that.
// place reference on this component
export const Compo1 = () => {
return (
<div ref={someRef}>
text 1
</div>
);
};
// same someRef reference passed as a prop here from some other component which doesn't talk to Compo1.
export const Compo2 = ({
someRef,
}) => {
// Do something with the reference value
return (
<div>
text 2
</div>
);
};
3
Answers
In addition to object refs (an object with
current
prop), refs also accept functions (ref callback functions). A function ref (likesetRef
) is passed the ref to the element when called.Instead of
useRef
, you can useuseState
instead, get the ref using the setter function, and set it as the state. You can then pass the state to another component.You can use a parent component in this way, or use context.
For example:
To create ref in another file and use it in two different components which are not linked with each other you can use
createRef
App.js
Comp1.js
constant.js
index.js
You could create a new global variable, for example:
And then you can use it like you normally would, by importing.o
See here a live version