Question: How to use "useRef" when it is passed through Portal?
See original GitHub issueHi. I create ref
in root component in my app. When i bind ref
to element, which is a child of another element that is render in the portal, ref “current” property is always undefined
.
Sandbox with example here: https://codesandbox.io/s/refs-through-portals-test-o5lqr
How can i use refs with portals with expected behaviour?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:9
Top Results From Across the Web
How can I call React useRef conditionally in a Portal wrapper ...
It creates portals with or without a parent target and cleans up completely. However React says not to call hooks from conditions, which...
Read more >Learn Portals & useRef for Modals – Complete Intro to React, v7
The "Portals & useRef for Modals" Lesson is part of the full, Complete Intro to React, v7 course featured in this preview video....
Read more >Portals and Refs - Complete Intro to React v5
Next create a file called Modal. js: import React, { useEffect, useRef } from "react"; import { createPortal } from "react-dom"; const modalRoot...
Read more >Working with React Fragments, Portals and Ref's
The best solution is what React provided for us, React.Fragment and this is how to use it. you can either import the name...
Read more >Hooks API Reference - React
useReducer; useCallback; useMemo; useRef; useImperativeHandle ... If the new state is computed using the previous state, you can pass a function to setState ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Ok, so here are some thoughts. When you want to apply some DOM-base library that’s what you usually do (and that’s probably what you want to do):
However, it is only safe to do if you pass the
ref
to a node that is available right after the component is mounted and until the component is unmounted.Some examples where it won’t work:
div
can be mounted later and then remounted multiply timesWho knows, what
Foobar
does to it children? Could just pass them through, could render conditionally.So, if you want to use this pattern, you need to move ref in such a way that is not rendered conditionally and is not wrapped in any custom components that doesn’t guarantee to pass through their children unconditionally.
That is not the case, the ref is fine, you just always log before it is populated