How do you fit an image in react native? - react-native

// How do you set the image on the top of the screen without losing the aspect ration?
[![import React, { Component } from 'react';
import { AppRegistry, View, Image, StyleSheet } from 'react-native';
export default class DisplayAnImageWithStyle extends Component {
render() {
return (
<View style={{flex:1}}>
<Image
resizeMode="contain"
style={{flex:1}}
source={{uri: 'https://i.pinimg.com/originals/ba/84/1c/ba841cc07934b508458a7faea62141a8.jpg'}}
/>
</View>
);
}
}
// Skip these lines if you are using Create React Native App.
AppRegistry.registerComponent(
'DisplayAnImageWithStyle',
() => DisplayAnImageWithStyle
);][1]][1]
// Here the liked image shows that it is not fitting well... it is not showing from the top... do you have any idea how I can set the image without any padding?
[1]: https://i.stack.imgur.com/LYNKn.png

So you might wanna use resizeMode: 'cover' with a height and width.
<Image
resizeMode="contain"
style={{ width: 200, height:220, resizeMode: 'cover'}}
source={{uri: 'https://i.pinimg.com/originals/ba/84/1c/ba841cc07934b508458a7faea62141a8.jpg'}}
/>
Here's an example https://snack.expo.io/HJTFg9tU4
Let me know if this works for you.

Related

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>

Why is my image (and child components) not showing with ImageBackground on React Native?

I am having an issue with the image just showing up on the application. Through search results, I mostly see the solution being that that the height and width was required and missing, but I have already implemented with no results.
I have looked at the routes multiple times and don't see any issues on that end.
Lastly, I thought it could be something to do with the image. I have altered the size and it worked with the <Image /> tag. However, I need it to be a background image.
Current Code
import React from 'react'
import { View, Text, StyleSheet, ImageBackground } from 'react-native';
import { MaterialCommunityIcons } from '#expo/vector-icons'
export default function TitleScreen () {
return (
<View>
<ImageBackground
source={require('../assets/images/title_background.png')}
style={styles.backgroundImage}
imageStyle={{resizeMode: 'cover'}}
>
<Text>testing</Text>
{/* <MaterialCommunityIcons
name={'cards-outline'}
size={100}
/> */}
</ImageBackground>
</View>
)
}
const styles = StyleSheet.create({
backgroundImage: {
flex: 1,
width: '100%',
height: '100%',
}
});
Folder Layout
assets
-- images
--- title_background.png
components
-- TitleScreen.js
Answered! The answer was to add flex: 1 to the parent view container - for those running into the same problem.

ImageBackground won't appear

I've been trying to render a background image, and it runs, but nothing appears. I'm running this through Android on Windows. This is the code below:
import React, { Component } from 'react';
import { View, Image, Text, ImageBackground } from 'react-native';
class Background extends Component {
render() {
return (
<ImageBackground
source={{uri: 'https://thumbs.dreamstime.com/b/purple-blue-textured-background-wallpaper-app-background-layout-dark-gradient-colors-vintage-distressed-elegant-78118630.jpg'}}
style={{flex: 1, width: '100%'}}
>
<View >
<Text>Test</Text>
</View>
</ImageBackground>
);
}
}
export default Background;
I'm not sure if the code just isn't properly pulling the image itself or if the styling needs to be adjusted. Thanks for the help!
Your ImageBackground component needs a height value in your style attribute. RN is picky about that.
import { ImageBackground } from 'react-native'
<ImageBackground
source={require('../assets/background.jpg')}
resizeMode={'cover'}
style={{ flex: 1, width: '100%' }}></ImageBackground>
Wrap your ImageBackground component within a Container component.
class Background extends Component {
render() {
return (
<Container>
<ImageBackground
source={{uri: 'https://thumbs.dreamstime.com/b/purple-blue-textured-background-wallpaper-app-background-layout-dark-gradient-colors-vintage-distressed-elegant-78118630.jpg'}}
style={{flex: 1, width: '100%'}}>
<View >
<Text>Test</Text>
</View>
</ImageBackground>
</Container>
);
}
}
for me only shows when i use
require()
like this post
ImageBackground not working when i call source from state
source={require( 'https://thumbs.dreamstime.com/b/purple-blue-textured-background-wallpaper-app-background-layout-dark-gradient-colors-vintage-distressed-elegant-78118630.jpg')}
(i tried to import image and call inside source but don't appears, even declaring in style height and width, only after use require(), why? i don't know)

react-native scrollview does now respect flex?

I'm learning flex layout for react native. This is my code:
import React, { Component } from 'react';
import {
Text,
View,
ScrollView
} from 'react-native';
const style = {
container: {
flex:1,
flexDirection:'column',
flexWrap:'nowrap',
alignItems:'stretch',
},
title: {
flex:1,
backgroundColor:'blue',
},
terms: {
flex:8,
flexDirection:'column',
backgroundColor:'red',
},
termsText: {
padding:15,
flex:1,
},
check: {
flex:1,
backgroundColor:'yellow',
}
};
export default class Home extends Component {
constructor(props)
{
super(props);
}
render() {
return (
<View style={style.container}>
<Text style={style.title}>Terms and Conditions</Text>
<ScrollView style={style.terms}>
<Text style={style.termsText}>You must comply, or die...</Text>
</ScrollView>
<Text style={style.check}>Check mark here (tap to agree to terms)</Text>
</View>
);
}
}
And the result is this:
This is not what I expected. I was expecting the red area to take up 80% of the vertical height because style.terms.flex == 8. If I changed the contents of my render to this:
render() {
return (
<View style={style.container}>
<Text style={style.title}>Terms and Conditions</Text>
<Text style={style.terms}>You must comply, or die...</Text>
<Text style={style.check}>Check mark here (tap to agree to terms)</Text>
</View>
);
}
I am then able to get the red area to become 80% vertical height. Why does ScrollView not respect style.terms.flex?
"Keep in mind that ScrollViews must have a bounded height in order to work, since they contain unbounded-height children into a bounded container (via a scroll interaction)." From the react native docs. What you can do is use the Dimensions API of react native and give the ScrollView 80% of device height instead.
More on ScrollView
Dimensions
Use Dimensions Api for ScrollView
const { width, height } = Dimensions.get('window');
<ScrollView style={{ height: height * 0.8 }}>
<Text style={style.termsText}>You must comply, or die...</Text>
</ScrollView>
height * 0.8 get the 80 percentage of height with respect to the screen size

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