I see that someone made this for it: https://github.com/brentvatne/react-native-linear-gradient
But is there support for it in RN itself? Something like
style = StyleSheet.create({
backgroundGradient: "vertical",
backgroundGradientTop: "#333333",
backgroundGradientBottom: "#666666"
});
Not at the moment. You should use the library you linked; they recently added Android support and it is by one of the main contributors of react-native.
Just export your gradient as SVG and use it using react-native-svg and when after you import your component set width and height and preserveAspectRatio="xMinYMin slice"to scale an SVG gradient at your needs.
First, run npm install expo-linear-gradient --save
You don't need to use an animated tag, but this is what I was using in my code.
inside colors={[ put your gradient colors ]}
then you can use something like this:
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
<AnimatedLinearGradient
colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
style={{ your styles go here }}/>
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
Here is a good choice for gradients for both platforms iOS and Android:
https://github.com/react-native-community/react-native-linear-gradient
There are others approaches like expo, however react-native-linear-gradient have worked better for me.
<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style={styles.linearGradient}>
<Text style={styles.buttonText}>
Sign in with Facebook
</Text>
</LinearGradient>
// Later on in your styles..
var styles = StyleSheet.create({
linearGradient: {
flex: 1,
paddingLeft: 15,
paddingRight: 15,
borderRadius: 5
},
buttonText: {
fontSize: 18,
fontFamily: 'Gill Sans',
textAlign: 'center',
margin: 10,
color: '#ffffff',
backgroundColor: 'transparent',
},
});
EXPO? Well, use this method Linear Gradient in React Native using EXPO. (Updated Nov. 2021)
No Pod Installs, No Errors, No additional linked files.
expo install expo-linear-gradient
Then
import { LinearGradient } from 'expo-linear-gradient';
<View style={styles.container}>
<LinearGradient
// Background Linear Gradient
colors={['rgba(0,0,0,0.8)', 'transparent']}
style={styles.background}
/>
<LinearGradient
// Button Linear Gradient
colors={['#4c669f', '#3b5998', '#192f6a']}
style={styles.button}>
<Text style={styles.text}>Sign in with Facebook</Text>
</LinearGradient>
</View>
Full Link here: https://docs.expo.dev/versions/latest/sdk/linear-gradient/
Here is a production ready pure JavaScript solution:
<View styles={{backgroundColor: `the main color you want`}}>
<Image source={`A white to transparent gradient png`}>
</View>
Here is the source code of a npm package using this solution:
https://github.com/flyskywhy/react-native-smooth-slider/blob/0f18a8bf02e2d436503b9a8ba241440247ef1c44/src/Slider.js#L329
Here is the gradient palette screenshot of saturation and brightness using this npm package:
https://github.com/flyskywhy/react-native-slider-color-picker
React Native hasn't provided the gradient color yet. But still, you can do it with a NPM package called react-native-linear-gradient or you can click here for more info
npm install react-native-linear-gradient --save
use import LinearGradient from 'react-native-linear-gradient'; in your application file
<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']}> <Text> Your Text Here </Text> </LinearGradient>
Looking for a similar solution I just came across this brand new tutorial, which lets you bridge a Swift gradient background (https://github.com/soffes/GradientView) library while walking through every step to get a working React component.
It is a step-by-step tutorial, allowing you to build your own component by bridging the swift and objective-c component into a usable React Native component, which overrides the standard View component and allows you to define a gradient like the following:
<LinearGradient
style={styles.gradient}
locations={[0, 1.0]}
colors={['#5ED2A0', '#339CB1']}
/>
You can find the tutorial here: http://browniefed.com/blog/2015/11/28/react-native-how-to-bridge-a-swift-view/
A little late to the party but the best solution IMO is using SVG gradient with react-native-svg which is included in most projects.
Here is a few lines versatile component that I use whenever I need a gradient:
Simple SVG Linear Gradient Component
import { View, StyleSheet, ViewProps } from 'react-native'
import Svg, { Defs, Rect, LinearGradient, Stop } from 'react-native-svg'
type GradientProps = { fromColor: string, toColor: string, children?: any, height?: number | string, opacityColor1?: number, opacityColor2?: number } & ViewProps
function Gradient({ children, fromColor, toColor, height = '100%', opacityColor1 = 1, opacityColor2 = 1, ...otherViewProps }: GradientProps) {
const gradientUniqueId = `grad${fromColor}+${toColor}`.replace(/[^a-zA-Z0-9 ]/g, '')
return <>
<View style={[{ ...StyleSheet.absoluteFillObject, height, zIndex: -1, top: 0, left: 0 }, otherViewProps.style]} {...otherViewProps}>
<Svg height='100%' width="100%" style={StyleSheet.absoluteFillObject}>
<Defs>
<LinearGradient id={gradientUniqueId} x1="0%" y1="0%" x2="0%" y2="100%">
<Stop offset="0" stopColor={fromColor} stopOpacity={opacityColor1} />
<Stop offset="1" stopColor={toColor} stopOpacity={opacityColor2} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill={`url(#${gradientUniqueId})`} />
</Svg>
</View>
{children}
</>
};
export default Gradient
See those example usages on snack
Yes React Native Support Gradient Use react-native-linear-gradient library.
Related
I'm trying to render an Image as background, but is not working, I don't know why. Here is my code.
<ImageBackground
source={require('../assets/images/logos/AFC.svg')}
resizeMode="cover"
style={styles.style}>
</ImageBackground>
React Native does not directly support using SVG format images. In order to use SVG Images you must use 3rd party libraries. I suggest using react-native-svg. Which is a great library and here is a tutorial you can use to set it up.
Your use case is to set it as a background image. It would be better to use png or jpg formats for use with Image Background component in react native. If you only have svg format of the image, then you can set it in View and control the view
You should use react-native-svg to display SVGs.
if you want a svg in background you can do this example below
import { View, Text, Dimensions } from 'react-native'
import React from 'react'
import AFCIcon from '../assets/images/logos/AFC.svg'
const SCREEN = Dimensions.get("screen");
const App = () => {
return (
<View style={{ flex: 1 }}>
<View style={{
position: "absolute",
width: "100%",
height: "100%",
bottom: 0,
zIndex: -1,
}}>
<AFCIcon width={SCREEN.width} height={SCREEN.height} />
</View>
{/* your code here */}
</View>
)
}
export default App
iOS is working fine BarCodeScanner take full screen but when i use android there is extra white space.
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : this._handleBarCodeScanned}
style={[StyleSheet.absoluteFill, { flex: 1 }]}
/>
I have also checked by giving a different style like but no luck
style={{
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}}
This seems to be an issue in recent versions of expo-barcode-scanner. One possible workaround is to explicitly set the dimensions of the BarCodeScanner to the dimensions of the screen:
import { Dimensions } from 'react-native';
<BarCodeScanner style={{
width: Dimensions.get('screen').width,
height: Dimensions.get('screen').height,
}} />
Note that setting it to the dimensions of the window, like you tried, does not work.
FrederikVds's answer not worked for me. So I have changed the expo camera which has the barcode scanner functionality too. You can do it like following:
import { Camera } from 'expo-camera'
<Camera
onBarCodeScanned={scanned ? undefined : this._handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
Optionally you can use ratio='16:9'.
If you need to use expo libraries in react-native cli, you should follow these setups
Here is the issue discussion: https://github.com/expo/expo/issues/5212
import { BarCodeScanner, BarCodeScannerResult } from
'expo-barcode-scanner'
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
export default function XYZ() {
return(
<BarCodeScanner
onBarCodeScanned={scanned ? undefined :
handleBarCodeScanned}
style={{ width: height - 188, height: height,
alignSelf: "center" }}
/>
)
}
Here I am using native-base latest version and using all the methods props but still my icons are not appearing in the header
import React, { Component } from "react";
import {
View,
Text,
StyleSheet
} from "react-native";
import {Header,Icon} from 'native-base'
class HomeScreen extends Component {
static navigationOptions = { header: null }
render() {
return (
<View style={{flex:1,backgroundColor:'#3q455c',width:"100%"}}>
<Header
placement="left"
leftComponent={{ icon: 'menu', color: 'white' }}
centerComponent={{ text: 'MY TITLE', style: { color: 'white' } }}
rightComponent={{ icon: 'home', color: 'white' }}
/>
</View>
);
}}
export default HomeScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
Here the header function is not showing in the header component
To get around this I did:
react-native link
react-native run-android
and the icons showed.
install react-native-vector-icons
npm install --save react-native-vector-icons
iOS:
react-native link react-native-vector-icons
Android:
Edit android/app/build.gradle ( NOT android/build.gradle ) and add the following:
project.ext.vectoricons = [
iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
and Use:
<Icon
type="MaterialIcons"
name="menu"
/>
document
For some reason, react-native-vector-icons wasn't linked to my project.
So:
react-native link react-native-vector-icons
made the trick for me.
Of course, you must have previously installed react-native-vector-icons module, something like:
npm install react-native-vector-icons --save
Keep coding, and let the code be with you!
In my case after adding below the line in app/build.gradle and re-create the build react-native run-android the icon will show.
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
Nirmal Dalmia's answer worked, but if you are using RN >= .60, you do have to install it before linking, as shown:
npm install react-native-vector-icons
react-native link react-native-vector-icons
This seems to be the case because, starting with .60, RN will autolink your npm dependencies. Since by default react-native-vector-icons is embedded within native-base, it won't autolink. I now get an error when running react-native run-android telling me not to manually link, but the icons are showing up.
I don't know why your code doesn't work.
Here is what I am using:
import React from "react";
import { SafeAreaView } from 'react-native';
import {
Container, Header, Title, Left, Icon, Right, Button, Body, Content, Text, Card, CardItem
} from "native-base";
export default class Test extends React.Component {
static navigationOptions = {
header: null
};
render() {
return (
<SafeAreaView style={{ flex: 1 }}>
<Container style={{ flex: 1, backgroundColor: '#fff' }}>
<Header style={{ backgroundColor: '#41b8f4' }}>
<Left>
<Button
transparent
onPress={() => console.log('button')}>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>Medical</Title>
</Body>
<Right />
</Header>
<Content padder style={{ flex: 1 }}>
<Card>
<CardItem>
<Left>
<Icon active name="md-person" />
<Text>text</Text>
</Left>
<Right>
<Icon name="arrow-forward" onPress={() =>
console.log('right')} />
</Right>
</CardItem>
</Card>
</Content>
</Container>
</SafeAreaView>
);
}
}
Native base uses window dimensions for Picker item and this ends in such issues. Add these lines to your Picker. It will solve your issue.
style={{ width: '80%' }}
placeholderStyle={{ maxWidth: '100%' }}
textStyle={{ maxWidth: '100%' }}
https://github.com/GeekyAnts/NativeBase/issues/2630#issuecomment-479847012
The icons in native base are served using react-native-vector-icons package. You don't need to install vector icons as it comes bundled with native base. I had the same problem of icons not showing up. All you need to do is link vector icons to your project.
react-native link react-native-vector-icons
After this, the icons should appear upon reinstalling the app.
Well for some reasons, I had to use this way :
<Icon type='MaterialIcons' name='menu' />
In opposition of this way :
<Icon android='md-menu' />
Can't find why though. This makes it more complicated to differentiate Android and iOS icons.
Have you installed the required peer dependencies for Native Base 2.x using the link command? https://docs.nativebase.io/docs/GetStarted.html
This fixed the issue for me:
npx react-native link
I'm building an application and I have a
problem with react-native icon. This is an image of the problem.
I followed this link and then I made sure the font is copied to android/app/src/main/assets/fonts, deleted the android/app/build folder. Finally I restarted react native package, but not throwing good result it such as first. How to fix this problem?
This is my code:
import React, { Component } from 'react';
import { Image, StyleSheet, View } from 'react-native';
import { Container, Header, Content, Card, CardItem, Right, Left, Thumbnail, Body, Text, Button, Icon } from 'native-base';
export default class SideMenu extends Component {
render() {
return (
<Container style={{ flex:1, backgroundColor:'#fcfcfc' }}>
<Content>
<Body style={{ justifyContent: 'center' }}>
<Image style={{ position: 'relative'}} source={require('../../../image/imac.jpg')}/>
<View style={bao.cover}>
<Thumbnail square source={require('../../../image/ava.jpg')} style={{borderRadius:40}}/>
<Text style={{ color:'#fff', flex:1, lineHeight:40, fontSize:18 }}> Vu Nguyen </Text>
</View>
</Body>
<Card>
<CardItem>
<Icon name="home" />
<Text>Home</Text>
</CardItem>
<CardItem>
<Icon name="news" />
<Text>Home</Text>
</CardItem>
</Card>
</Content>
</Container>
);
}
}
const bao = StyleSheet.create({
cover:{
position:'absolute',
flex: 1,
flexDirection: 'row',
marginLeft:30,
top: 170
}
})
Make sure the icon name you are is there in whatever Icon set you are using like (FontAwesome, Ionicons) etc.
"news" icon is available in Entypo
The issue was solved for me by:
react-native link
and then:
react-native run-android
I had a similar problem where the node_modules/react-native-vector-icons/glyphmaps/FontAwesome5Pro.json was outdated. I was trying to get the "bible" icon from FontAwesome v5.3.1, however resources from react-native-vector-icons still seem to be from 5.0. So a "?" was appearing.
I tried to npm install the latest version of react-native-vector-icons, but the problem persisted.
I manually copied the FontAwesome5Pro.json content from the Github repo. After restarting my simulator the question marks had become the icons I was looking for.
it's because native-base have some icons and some are not present.
so try to import the icon from it's original module instead of native-base
try this
import Icon from 'react-native-ionicons'
or other font libraries
import Icon from 'react-native-fontawesome'
instead of this
import { Icon } from 'native-base'
If anyone is facing this issue please paste this line in your app/build.gradle and re-run the project.
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
try this
react-native link react-native-vector-icons
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