React native Responsive layout in Functional component - react-native

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

Related

How can I send a text from my React Native App without leaving my app?

I have a React Native - Expo Android mobile app that we are using to send text messages out to customers to let them know when we arrive, currently using Twilio and it is expensive, I have tried many code examples to send a text message directly from the phone and they all seem to go outside the app and want to send the text message through the phone's default message app eg Messages, we want to stay in our app and send them.
My question is:
Is there a way to do this? If so how?
If not what is a cheaper solution than Twilio to send texts that will work in a React Native - Expo app?
I have been trying to find a solution now for quite awhile.
Thanks in advance for your help!
I have tried many code examples with no luck, here is an example of the code I have tried:
Here is an example of the code I am trying:
/** #format */
import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View } from "react-native";
import { Entypo } from "#expo/vector-icons";
import Communications from "react-native-communications";
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>SmS App</Text>
<Entypo
name="message"
size={70}
color="#202668"
onPress={() => Communications.text(
'3435447131',
'Hello'
)}
/>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
textStyle: {
fontWeight: "bold",
fontSize: 30,
color: "#2AB4F3",
bottom: 10,
},
});

How to translate mobile app text using language drop-down inside react-native app?

I want to add translate drop-down inside mobile app to translate the app text without using language json file.
I just want to add the select list at the top of app to change the language of text, like this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_google_translate
Is this possible with react native app?
Here is an example of how you can achieve that.
Working Example: Expo Snack
import React, { useState } from 'react';
import { Text, View, StyleSheet, Picker } from 'react-native';
import Constants from 'expo-constants';
const engToHindi = {
english: 'hello',
hindi: 'नमस्कार',
};
export default function App() {
const [language, setLanguage] = useState('english');
return (
<View style={styles.container}>
<Picker
selectedValue={language}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue) => setLanguage(itemValue)}>
<Picker.Item label="English" value="english" />
<Picker.Item label="हिन्दी" value="hindi" />
</Picker>
<Text>{engToHindi[language]}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
Online Implementation using Google Translate API would be possible but I don't have the API keys so could not give you the example of that implementation.

My React Native application is taking up ludicrous amount of space on my device

My React Native app I've written for benchmarking purposes in my Bachelors thesis is taking up crazy amount of space on my device (iPhone).
70,5MB to be precise. Since application size is a metric I am comparing in my research one could only wonder if this could be true..
Am I doing something wrong? (I am a beginner with React Native)
I will provide my entire code for the benchmark example where I've implemented recursive fibonacci (for benchmarking)
import React, {useState} from 'react';
import {
View,
Text,
Button,
TextInput,
StyleSheet,
} from 'react-native';
export default function App(){
const [n,setN] = useState(0);
const [Output,setOutput] = useState(0);
return(
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center"
}}>
<Text>Enter a number for N: {Output}</Text>
<TextInput
style ={styles.input}
placeholder ='Test'
onChangeText={(val) => setN(val)}/>
<Button style={styles.knapp} title ="Start" onPress={() => start()} ></Button>
</View>
);
function start(){
setOutput(fibonacci(n));
}
function fibonacci(n){
if(n <= 2)
return 1;
else
return fibonacci(n-2) + fibonacci(n -1);
}
}
const styles = StyleSheet.create({
input:{
borderWidth: 1,
marginTop: 30,
marginBottom: 30,
width: 100,
height:20,
color: '#777',
borderColor: '#777'
},
})
The Native Swift application in comparison only takes up around 465KB.
Are React Native apps usually this heavy?
I can also mention that the project was generated through
react-native init projectname
and I started coding from there.

swiping on react-native-snap-carousel is not working as expected

I am trying to use react-native-snap-carousel but however, the swiping effect is not working as expected - it is often difficult to swipe left and right, it requires user to swipe harder to move to another picture (as illustrated in the link below).
Swiping issue with React Native Snap Carousel
I am not able to find any documented soluton but I found one possible prop - swipeThreshold. I try various value, but still the issue persist.
Does anyone know the solution to this?
I suggest you to use react-native-image-slider.
it's flexible and easy to use.
https://www.npmjs.com/package/react-native-image-slider
I made a component named slider.js:
import React, { Component } from 'react';
import {
View,
StyleSheet,
Image,
} from 'react-native';
import ImageSlider from 'react-native-image-slider';
export default class Slider extends Component {
render() {
return (
<ImageSlider
loop
autoPlayWithInterval={3000}
images={this.props.dataSource}
customSlide={({ index, item, style, width }) => (
<View key={index} style={[style, styles.customSlide]}>
<Image source={{ uri: item }} style={styles.customImage} />
</View>
)}
/>
);
}
}
const styles = StyleSheet.create({
customImage: {
height: 180,
marginRight: 20,
marginLeft: 20,
borderWidth: 1,
borderRadius: 10,
marginTop: 8,
},
customSlide: {
backgroundColor: '#eee',
},
});
you can add this to your project and use it wherever you need it like this:
import Slider from '../component/slider';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
images: [
'https://placeimg.com/640/480/nature',
'https://placeimg.com/640/480/tech',
'https://placeimg.com/640/480/animals',
'https://placeimg.com/640/480/tech',
],
}
render() {
return (
<View style={{flex: 1, backgroundColor: '#eee'}}>
<Slider dataSource={this.state.images} />
</View>
);
}
}

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

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