Reputation: 11
I have a problem, I would like to access to a DOM Element with a global variable for using it in all my methods, I tried to access it with "this.refs" but it seems to be only for forms and input ? Maybe you know a better way to do it ? Here is some of my code :
` import React from 'react';
var isSmall = false;
var isMedium = false;
var isLarge = true;
class App extends React.Component {
openIframe()
{
var iframe = document.createElement('iframe');
var siteUrl = document.getElementById('siteUrl').value;
var header = document.getElementById('header');
iframe.src = "";
iframe.src = siteUrl;
iframe.setAttribute('id', 'iframe');
header.classList.add('scrollUp');
setTimeout( function (){
document.getElementById("iframe_append").appendChild(iframe);
},500);
}
reloadIframe ()
{
var iframe = document.getElementById('iframe');
iframe.src = iframe.src;
}`
Upvotes: 1
Views: 2206
Reputation: 564
You can use ref callback on HTML elements and set local variable of that component.
input type="file" id="file" ref={(input) => { this.textInput = input; }}
and to use it inside component call
this.textInput.focus();
For functional components you can use refs
input type="file" id="file" ref="uploader"
and to use it inside component call
this.refs.uploader.focus();
Details: Refs
Upvotes: 1
Reputation: 1559
It is not recommended to access DOM in React instead you can make component and place it in your components hierarchy in your desired place.
Upvotes: 0
Reputation: 752
1) You can use ref callbacks for both React components and any DOM element. Here is a reference: https://reactjs.org/docs/refs-and-the-dom
2) You should avoid global variables. Instead, you can export variable using ES6 modules syntax and access in any other file by importing it. For example:
App.js
export const someVar = 'valueOfSomeVar';
someOtherFile.js
import { someVar } from 'pathToApp.js';
console.log(someVar); // 'valueOfSomeVar'
Upvotes: 0