Icaro Rios
Icaro Rios

Reputation: 31

React Native getElementById

want to do a

document.getElementById('js-pjax-loader-bar')

from https://github.com/facebook/react-native

And i don't know how o get it!

I try:

const jsCode = "document.getElementById('js-pjax-loader-bar')";
return (     
  <WebView
    source={{uri: 'https://github.com/facebook/react-native'}}
    onMessage={this._onMessage}
    injectedJavaScript={jsCode }
    style={{marginTop: 20}}
  />
);

Possibly the script run, but i don't know how to get de result.

Upvotes: 2

Views: 4642

Answers (2)

I think you need set javaScriptEnabled property as true and use a setTimeout to wait while DOM load.

const jsCode = "setTimeout(function() {document.getElementById('js-pjax-loader-bar');}, 2000)";

And the WebView

<WebView
    javaScriptEnabled={true}  
    source={{uri: 'https://github.com/facebook/react-native'}}
    onMessage={this._onMessage}
    injectedJavaScript={jsCode }
    style={{marginTop: 20}}
/>

Too can add a alert inside the jsCode to test.

to recive on _onMessage function you need use a window.postMessage

const jsCode = "setTimeout(function(){window.postMessage(JSON.stringify(document.getElementById('js-pjax-loader-bar')),'https://github.com/facebook/react-native');}, 2000)";

and the _onMessage must be like

_onMessage(data) {
    var element = JSON.parse(data.nativeEvent.data);
}

Upvotes: 2

Amirhosein Shirani
Amirhosein Shirani

Reputation: 393

React is a virtual dom , and generate bundle after rendering (client side rendering) for use ids or something like that is better to use ref in react

Upvotes: 1

Related Questions