In my webpage, there is a form that is loaded via an iframe.
I can access the iframe with a ref:
const formRef = useRef(null)
<FormIframe ref={formRef} />
The iframe will return a bunch of JSX, and inside there, I know that there is an element that has the id of "first_name"
<input id="first_name" />
How do I access that element using the ref so that I can do stuff with it? The following does NOT work:
const el = formRef?.current?.getElementById("first_name")
I also tried using document with getElementById in a useEffect but that also didn’t work. It returned null:
useEffect(() => {
if (document) {
const el = document.getElementById("first_name")
console.log(el)
}
}, [])
Any ideas?
3
Answers
You can access it as:
your problem is that your form is in a iframe.
When working with an iframe, accessing elements inside it can be a bit different from accessing elements in the main document. In your case, since you have a reference (formRef) to the iframe, you can use the contentWindow property to access the document inside the iframe and then retrieve the element by its ID. Here’s how you can modify your code to achieve that:
Also can you look at
get iframe elements in react using ref
React – Accessing inline created iframe elements
The same idea is related.
Import the useRef hook from the React package at the top of your component file:
Inside your functional component, declare a ref variable using the useRef hook:
Assign the ref to the JSX element you want to reference using the ref attribute:
You can now access the referenced element using the current property of the ref:
Here’s an example that demonstrates these steps:
In the above example, myRef is used to reference the element. When the button is clicked, the handleClick function is triggered, and it logs the text content of the referenced element to the console.
Remember to check if the ref.current value is not null before accessing or manipulating the referenced element, as it will initially be null until the component is rendered and the ref is assigned.