React Native Webview not loading any url (React native web view not working) - react-native

I am trying to implement react native webview component in my application, but the web view is not loading any url its just showing the white page.
var React = require('react-native');
var{
View,
Text,
StyleSheet,
WebView
} = React;
module.exports = React.createClass({
render: function(){
return(
<View style={styles.container}>
<WebView source={{uri: 'https://m.facebook.com'}} style= {styles.webView}/>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex:1,
backgroundColor: '#ff00ff'
},webView :{
height: 320,
width : 200
}
});
Below is the screenshot of the output .

I had this issue. WebView would render when it was the only component returned, but not when nested in another View component.
For reasons I'm not entirely sure of the issue was resolved by setting a width property on the WebView component.
class App extends React.Component {
render() {
return (
<View style={styles.container}>
<WebView
source={{uri: 'https://www.youtube.com/embed/MhkGQAoc7bc'}}
style={styles.video}
/>
<WebView
source={{uri: 'https://www.youtube.com/embed/PGUMRVowdv8'}}
style={styles.video}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-between',
},
video: {
marginTop: 20,
maxHeight: 200,
width: 320,
flex: 1
}
});

I'm facing same issue. What I observed is that WebView doesn't work if it's nested. If component returns just WebView, then everything is fine.

Using the answers from other users, I was able to get my react native with webview working both inside a view and outside a view. My problem came down to two things. Being on the android emulator and behind a proxy, I just had to go to my browser (chrome) in the android emulator and sign in to the corporate proxy. Secondly, some sites work and others will not work. Whether the webview was nested or not inside of a View tag, some sites like cnn.com and slack.com etc will work fine, but no matter what settings I tried for google.com it wouldn't work (even though the proxy will definitely allow google.com) Lastly, when I rebuild my application and push to the emulator the new app, sometimes it took an inordinately long time to load any site. But once the site was loaded, the links are quick and responsive. So if you don't at first see something after a build, also be patient. Hope this helps someone else.
My final app.js
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Dimensions
} from 'react-native';
import { WebView } from 'react-native';
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={{flex:1}}>
<WebView
style={styles.webview}
source={{uri: 'https://www.slack.com'}}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={false}
scalesPageToFit={true} />
</View>
);
}
}
const styles = StyleSheet.create({
webview: {
flex: 1,
backgroundColor: 'yellow',
width: deviceWidth,
height: deviceHeight
}
});

WebView works well on Android. However you need to enable javascript and dom storage for some web pages.
<WebView style={styles.webView}
source={{uri: 'https://google.com/'}}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={true}
>
</WebView>

If you want the component to render the entire page, you need to wrap it with View that has flex: 1. The code below works for me:
<View style={{flex:1, alignItems: 'flex-end'}}>
<WebView
source={{uri: this.state.webContentLink}}
startInLoadingState={true}
scalesPageToFit={true} />
</View>

WebView is being moved to react-native-webview
.
None of the other answers worked except this method:
npm install --save react-native-webview
Then use it as follows:
<View style={{ flex: 1, alignItems: 'flex-end' }}>
<WebView
source={{
uri: 'https://www.yahoo.com',
}}
startInLoadingState={true}
scalesPageToFit={true}
style={{
width: 320,
height: 300,
}}
/>
</View>

<View>
<WebView
source={{uri: this.props.link}}
style={styles.webview}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={true}
/>
</View>
and style as follows:
const React = require('react-native');
const { Dimensions } = React;
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
export default {
webview: {
width: deviceWidth,
height: deviceHeight
}
};
All this to deal with bad webview dimension, so just set a specific height and specific width too (deviceHeight and deviceWidth as the example above).

As of June 2020 (noting the date because React Native answers seem to become out-of-date quickly), the simplest solution to this appears to be:
import React from 'react'
import { View, StyleSheet } from 'react-native'
import { WebView } from 'react-native-webview'
export const ComponentWithWebView = () => {
return (
<View style={styles.view}>
<WebView source = {{uri: 'https://www.google.com/'}} />
</View>
)
}
const styles = StyleSheet.create({
view: {
alignSelf: 'stretch',
flex: 1,
}
}
This results in a WebView filling the available space and being nested within a View. I believe the typical problems faced when placing a WebView within a View is that View expects children to force the View to expand (that is, a Text component would take up some amount of width and height which the View then accommodates). WebView, on the other hand, expands to the size of the parent component unless a style is passed specifying the width. Therefore, a simple <View><WebView /></View> results in a 0 width and nothing shown on the screen. The earlier solutions of setting the WebView width work well but require either the device dimensions to be fetched (which might not be the desired width) or for the View to have an onLayout function AND have some way to expand the View to the desired space. I found it easiest to just apply the flex: 1 and alignSelf: 'stretch' for the View to fill the space as desired and then WebView to automatically follow suit.
Hope this helps someone before it becomes obsolete!

I ran into the same issue recently. And I found that
alignment: 'center'
was causing the issue for me. I commented it and the webView got loaded immediately.
I found the solution here :
https://github.com/facebook/react-native/issues/5974
'brunocvcunha's' response worked for me.

Let me give the simplest example which will work seamlessly:
import React from 'react';
import { WebView } from 'react-native';
export default class App extends React.Component {
render() {
return (
<WebView
source={{uri: 'https://github.com/facebook/react-native'}}
/>
);
}
}
Do not add your WebView component within a view that created problem and webview url is not rendered rather styles of view will be shown.

I had the same issue and spent a day attempting to fix it. I copied in the UIExplorer webview example, and that didn't work.
I ultimately ended up upgrading react and creating a new react-native project and copying the files in there, and that fixed it.
I wish I had a better answer as to why that fixed it, but hopefully that helps

Below is piece of the code which worked for me.
render: function(){
return(
<View style={styles.container}>
<WebView url={'https://m.facebook.com'} style= {styles.webView}/>
</View>
);
}

I am doing React Native Webview, Could you please suggest me how to makeWebview loading the uri
render() {
return (
<Modal
animationType="slide"
ref={"webModal"}
style={{
justifyContent: 'center',
borderRadius: Platform.OS === 'ios' ? 30 : 0,
width: screen.width,
height: screen.height,borderColor:'red',
borderWidth: 5
}}
position='center'
backdrop={false}
onClosed={() => {
// alert("Modal closed");
}}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 20, top: 10 }} >
<Text style={{ fontSize: 24, fontWeight: '700' }}>
Interests
</Text>
<Icon name="ios-close" size={40} color='purple' onPress={() => { this.refs.webModal.close() }} />
</View>
<WebView
source={{ uri: this.state.link }}
style={{ marginTop: 20,borderColor:'green',
borderWidth: 5 }}
/>
</Modal>
);
}
}

import { WebView } from 'react-native'; is deprecated
use below line instead
npm install react-native-render-html#4.1.2 --save
then
import HTML from 'react-native-render-html';
react-native-render-html starting with version 4.2.0, react-native-webview is now a peer dependency. As a result, you need to install it yourself.

Try
<WebView
source={{ uri: "https://inhall.in/" }}
style={Styles.webView}
javaScriptEnabled={true}
scalesPageToFit />
javaScriptEnabled={true} might help

Related

React native Responsive layout in Functional component

Below is the basic code for Responsive layout using npm package(react-native-responsive-screen). This is working fine as expected in Class component. But, I want to change the below code to Functional component. I have almost changed everything. Initially no error when i load the app in portrait/landscape mode. Once i change it to landscape/portrait, it will come up with some error.
Here is the link of Original source. https://github.com/marudy/react-native-responsive-screen/blob/master/examples/responsive-screen-orientation-change/README.md
import React, { useEffect, useState } from 'react';
import { StyleSheet, Dimensions } from 'react-native';
import { Container, View, Button, Text} from "native-base";
import {widthPercentageToDP as wp,
heightPercentageToDP as hp,
listenOrientationChange as lor,
removeOrientationListener as rol } from 'react-native-responsive-screen';
const Responsive = () =>
{
useEffect( () =>
{
lor();
return () => rol()
},[])
const styles = StyleSheet.create({
container: { flex: 1, alignItems: 'center', justifyContent:'center' },
title: {
backgroundColor: 'gray',
height: hp('10%'),
width: wp('80%'),
alignItems: 'center',
justifyContent:'center',
marginVertical: wp('10%'),
},
myText: {
textAlign:'center',
color:'white',
fontSize: hp('5%') // End result looks like the provided UI mockup
},
buttonStyle:
{
height: hp('8%'), // 70% of height device screen
width: wp('30%'),
marginHorizontal: wp('10%'),
},
buttonContainer:
{
flexDirection:'row',
marginBottom: wp('10%'),
},
paraContainer:
{
width: wp('80%'),
},
paraText:
{
textAlign:'justify'
}
});
return (
<Container>
<View style={styles.container}>
<View style={styles.title}>
<Text style={styles.myText}>Screen title with 50% width</Text>
</View>
<View style={styles.buttonContainer}>
<Button success style={styles.buttonStyle}><Text>Button 1</Text></Button>
<Button success style={styles.buttonStyle}><Text>Button 2</Text></Button>
</View>
<View style={styles.paraContainer}>
<Text style={styles.paraText}>
As mentioned in "How to Develop Responsive UIs with React Native" article, this solution is
already in production apps and is tested with a set of Android, iOS emulators of different
screen
specs, in order to verify that we always have the same end result.
</Text>
</View>
</View>
</Container>
);
}
export default Responsive;
Thanks in Advance.
It is not due to your code, it is due to library limitation. Current version of library still does not support functional components.
There is an open issue and PR regarding that open
issue: https://github.com/marudy/react-native-responsive-screen/issues/82
PR: https://github.com/marudy/react-native-responsive-screen/pull/70
If you still want to continue with this library, just use the head of that PR in your package.json and it should work.
"react-native-responsive-screen": "marudy/react-native-responsive-screen#70/head",
Make sure to delete node_module and perform yarn or npm install

WebView inconsistently showing white screen react-native

I'm using a WebView to show an iframe of a twitch-stream in my react-native app, however at some points when it renders the WebView only shows up as a blank white screen until you scroll/move the UI and at other times it works as intended.
There are no errors emitted when the WebView is blank, it seems to load as intended so not really sure why it just shows a blank white screen.
Here is the WebView code:
<Animated.View
style={{
height: anim,
width: width,
overflow: 'hidden',
}}
>
<WebView
onLoadEnd={() => {
useAnimation()
}}
source={{
uri: `https://host.com/iframe/?channel=${channelName}`,
}}
style={{
height: heightByRatio,
width: width,
flex: 0,
}}
mediaPlaybackRequiresUserAction={false}
allowsInlineMediaPlayback={true}
/>
</Animated.View>
I had a very similar issue of webviews sometimes loading blank on android devices. I can't say I figured out why it was happening, but I solved it by delaying the load of the webview and putting a 2px border around the container wrapping the webview. Neither solution worked on its own, both were needed.
export default class WebviewExample extends Component<Props> {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
setTimeout(() => {
this.setState({loadWebview: true});
});
}
render() {
return (
<View style={styles.view}>
{this.state.loadWebview &&
<WebView />
}
</View>
);
}
}
const styles = StyleSheet.create({
view: {
borderWidth: 2,
borderColor: 'transparent',
}
});

Position absolute not working inside ScrolView in React native

I was trying to position a button on the bottom right of the screen like the picture below:
So, basically I had a Scrollview with the button inside like so:
import React, { Component } from 'react'
import { ScrollView, Text, KeyboardAvoidingView,View,TouchableOpacity } from 'react-native'
import { connect } from 'react-redux'
import { Header } from 'react-navigation';
import CreditCardList from '../Components/credit-cards/CreditCardList';
import Icon from 'react-native-vector-icons/Ionicons';
import Button from '../Components/common/Button';
// Styles
import styles from './Styles/CreditCardScreenStyle'
import CreditCardScreenStyle from './Styles/CreditCardScreenStyle';
class CreditCardScreen extends Component {
render () {
return (
<ScrollView style={styles.container}>
<CreditCardList />
<TouchableOpacity style={CreditCardScreenStyle.buttonStyle}>
<Icon name="md-add" size={30} color="#01a699" />
</TouchableOpacity>
</ScrollView>
)
}
}
My styles:
import { StyleSheet } from 'react-native'
import { ApplicationStyles } from '../../Themes/'
export default StyleSheet.create({
...ApplicationStyles.screen,
container:{
marginTop: 50,
flex: 1,
flexDirection: 'column'
},
buttonStyle:{
width: 60,
height: 60,
borderRadius: 30,
alignSelf: 'flex-end',
// backgroundColor: '#ee6e73',
position: 'absolute',
bottom: 0,
// right: 10,
}
})
The problem is that the absolute positioning does not work at all when the button is inside the ScrollView. But...If I change the code to look like this:
import CreditCardScreenStyle from './Styles/CreditCardScreenStyle';
class CreditCardScreen extends Component {
render () {
return (
<View style={styles.container}>
<ScrollView >
<CreditCardList />
</ScrollView>
<TouchableOpacity style={CreditCardScreenStyle.buttonStyle}>
<Icon name="md-add" size={30} color="#01a699" />
</TouchableOpacity>
</View>
)
}
}
Then it works !! Whaat? Why? How? I don't understand why this is happening and I would appreciate any information about it.
This might be inconvenient but is just how RN works.
Basically anything that's inside the ScrollView (in the DOM/tree) will scroll with it. Why? Because <ScrollView> is actually a wrapper over a <View> that implements touch gestures.
When you're using position: absolute on an element inside the ScrollView, it gets absolute positioning relative to its first relative parent (just like on the web). Since we're talking RN, its first relative parent is always its first parent (default positioning is relative in RN). First parent, which in this case is the View that's wrapped inside the ScrollView.
So, the only way of having it "fixed" is taking it outside (in the tree) of the ScrollView, as this is what's actually done in real projects and what I've always done.
Cheers.
i suggest to use "react-native-modal".
you can not use position: 'absolute' to make elements full size in ScrollView
but you can do it by
putting that element in modal wrapper.
below are two examples. first one doesnt work but the second one works perfectly.
first way (doesnt work):
const app = () => {
const [position, setPosition] = useState('relative')
return(
<ScrollView>
<Element style={{position: position}}/>
<Button
title="make element fixed"
onPress={()=> setPosition('absolute')}
/>
</ScrollView>
)
}
second way (works perfectly):
const app = () => {
const [isModalVisible, setIsModalVisible] = useState(false)
return(
<ScrollView>
<Modal isModalVisible={isModalVisible}>
<Element style={{width: '100%', height: '100%'}}/>
</Modal>
<Button
title="make element fixed"
onPress={()=> setIsModalVisible(true)}
/>
</ScrollView>
)
}
for me this worked:
before:
<View>
<VideoSort FromHome={true} />
<StatisticShow style={{position:'absulote'}}/>
</View>
after:
<View>
<ScrollView>
<VideoSort FromHome={false} />
</ScrollView>
<View style={{position:'relative'}}>
<StatisticShow style={{position:'absulote'}}/>
</View>
</View>

setNativeProps Change Value for Text Component React Native Direct Manipulation

I want to directly update the value of a component due to performance reasons.
render(){
<View>
<Text style={styles.welcome} ref={component => this._text = component}>
Some Text
</Text>
<TouchableHighlight underlayColor='#88D4F5'
style={styles.button}>
<View>
<Text style={styles.buttonText}
onPress={this.useNativePropsToUpdate.bind(this)}>
Iam the Child
</Text>
</View>
</TouchableHighlight>
</View>
}
This is the method I use to update the text component. I dont know if I am setting the right attribute/ how to figure out which attribute to set:
useNativePropsToUpdate(){
this._text.setNativeProps({text: 'Updated using native props'});
}
Essentially trying to follow the same approach from this example:
https://rnplay.org/plays/pOI9bA
Edit:
When I attempt to explicitly assign the updated value:
this._text.props.children = "updated";
( I know this this the proper way of doing things in RN ). I get the error "Cannot assign to read only property 'children' of object'#'"
So maybe this is why it cant be updated in RN for some reason ?
Instead of attempting to change the content of <Text> component. I just replaced with <TextInput editable={false} defaultValue={this.state.initValue} /> and kept the rest of the code the same. If anyone know how you can change the value of <Text> using setNativeProps OR other method of direct manipulations. Post the answer and ill review and accept.
The text tag doesn't have a text prop, so
this._text.setNativeProps({ text: 'XXXX' })
doesn't work.
But the text tag has a style prop, so
this._text.setNativeProps({ style: { color: 'red' } })
works.
We can't use setNativeProps on the Text component, instead, we can workaround and achieve the same result by using TextInput in place of Text.
By putting pointerEvent='none' on the enclosing View we are disabling click and hence we can't edit the TextInput (You can also set editable={false} in TextInput to disbale editing)
Demo - Timer (Count changes after every 1 second)
import React, {Component} from 'react';
import {TextInput, StyleSheet, View} from 'react-native';
class Demo extends Component {
componentDidMount() {
let count = 0;
setInterval(() => {
count++;
if (this.ref) {
this.ref.setNativeProps({text: count.toString()});
}
}, 1000);
}
render() {
return (
<View style={styles.container} pointerEvents={'none'}>
<TextInput
ref={ref => (this.ref = ref)}
defaultValue={'0'}
// editable={false}
style={styles.textInput}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 0.7,
justifyContent: 'center',
alignItems: 'center',
},
textInput: {
fontSize: 60,
width: '50%',
borderColor: 'grey',
borderWidth: 1,
aspectRatio: 1,
borderRadius: 8,
padding: 5,
textAlign: 'center',
},
});
export default Demo;
As setNativeProps not solving the purpose to alter the content of <Text />, I have used below approach and is working good. Create Simple React Component like below...
var Txt = React.createClass({
getInitialState:function(){
return {text:this.props.children};
},setText:function(txt){
this.setState({text:txt});
}
,
render:function(){
return <Text {...this.props}>{this.state.text}</Text>
}
});

Setting component height to 100% in react-native

I can give the height element of style numeric values such as 40 but these are required to be integers. How can I make my component to have a height of 100%?
check out the flexbox doc. in the stylesheet, use:
flex:1,
Grab the window height into a variable, then assign it as the height of the flex container you want to target :
let ScreenHeight = Dimensions.get("window").height;
In your styles :
var Styles = StyleSheet.create({ ... height: ScreenHeight });
Note that you have to import Dimensions before using it:
import { ... Dimensions } from 'react-native'
flex:1 should work for almost any case. However, remember that for ScrollView, it's contentContainerStyle that controls the height of view:
WRONG
const styles = StyleSheet.create({
outer: {
flex: 1,
},
inner: {
flex: 1
}
});
<ScrollView style={styles.outer}>
<View style={styles.inner}>
</View>
</ScrollView>
CORRECT
const styles = StyleSheet.create({
outer: {
flex: 1,
},
inner: {
flex: 1
}
});
<ScrollView contentContainerStyle={styles.outer}>
<View style={styles.inner}>
</View>
</ScrollView>
You can simply add height: '100%' into your item's stylesheet.
it works for me
most of the time should be using flexGrow: 1 or flex: 1
or you can use
import { Dimensions } from 'react-native';
const { Height } = Dimensions.get('window');
styleSheet({
classA: {
height: Height - 40,
},
});
if none of them work for you try it:
container: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
}
Try this:
<View style={{flex: 1}}>
<View style={{flex: 1, backgroundColor: 'skyblue'}} />
</View>
You can have more help in react-native online documentation (https://facebook.github.io/react-native/docs/height-and-width).
I was using a ScrollView, so none of these solutions solved my problem. Until I tried contentContainerStyle={{flexGrow: 1}} prop on my scrollview. Seems like without it -scrollviews will just always be as tall as their content.
My solution was found here: React native, children of ScrollView wont fill full height
<View style={styles.container}>
</View>
const styles = StyleSheet.create({
container: {
flex: 1
}
})
I looked at lots of these solutions, and none worked across React Native mobile and web.
Tracking the screen height using Dimensions API is one way that does work, but this can be innacurate on some mobile devices. The best solution I found was to use this on your element:
<View style={{ height:Platform.OS === 'web' ? '100vh' : '100%' }}
/* ... your application */
</View>
Please also note the caveat with ScrollView as mentioned here.
I would say
<View
style={{
...StyleSheet.absoluteFillObject,
}}></View>
In this way, you can fill the entire screen without caring about, flex, width, or height