How to change the style with props - javascript

How to change the style in React Native?
I need to change the color of the text when it is true or false
here is my code:
Styles Area
LIVE:{
color: "red"
},
Comp: {
color: "green"
},
Main
<Text style={MyCardStyle.AnyText}>{isLive == false ? /* MyCardStyle.Comp */ : /* MyCardStyle.LIVE */ }</Text>
// The commented out codes have error as "Objects are not valid as a React child"
Props
<MyMatchCard
isLive={true}
/>
Here i want to change the color of the Text to green when its false or red when its true
How to actually apply the color without getting an error?

One way to do it is to change the style object to function instead. That function will take a parameter that will be used to define the text color:
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants'
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
const MyText = ({isLive}) => {
return (
<Text style={styles.text(isLive)}>
Change code in the editor and watch it change on your phone! Save to get a shareable url.
</Text>
)
}
export default function App() {
return (
<View style={styles.container}>
<MyText isLive />
<MyText />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
text: (isLive) => ({
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
color: isLive ? 'green' : 'black'
}),
});

You can also pass the condition to the style prop
const MyText = ({isLive}) => {
return (
<Text style={{color: isLive? 'green' : 'red' }}>
Your text
</Text>
)
}

Related

native base Text showing uppercase on only some screens

I am using Native Base Text in 2 different components. In this one by default, the Text is shown in uppercase, unless I add uppercase={false}.
export const ActionButton: React.FunctionComponent<ActionButtonProps> = ({
style,
disabled,
buttonText,
onPress,
}) => {
return (
<Button rounded onPress={onPress} disabled={disabled} style={[styles.button, style]}>
<Text uppercase={false} style={styles.text}>{buttonText}</Text>
</Button>
);
};
const styles = StyleSheet.create({
button: {
width: moderateScale(160),
height: moderateScale(50),
backgroundColor: '#31C283',
justifyContent: 'center',
},
text: { color: 'white', fontSize: moderateScale(13, 0.7), fontWeight:'600' },
});
However, in the following component, text is lowercase, even without using uppercase=false. Why is it different in the two components? What am I doing wrong?
export const TripOptionsSelector: React.FunctionComponent = () => {
const navigation = useNavigation();
return (
<View style={styles.offerContainer}>
<Text style={styles.offerText}>Jetzt</Text>
<Text style={styles.offerText}>1 Person</Text>
<Text style={styles.offerText} onPress={()=>navigation.navigate('TripFilter')}>Filter</Text>
</View>
);
};
const styles = StyleSheet.create({
offerContainer: {
flexDirection: 'row',
},
offerText: {
color: 'white',
marginRight: moderateScale(20),
paddingHorizontal: 10,
fontSize: moderateScale(14),
borderColor: 'white',
borderWidth: 1,
borderRadius: 10,
alignItems: 'center',
justifyContent: 'center',
},
});
Codesandbox: https://snack.expo.io/#nhammad/trusting-hummus
There is nothing wrong with Text,
actually Native Base Button makes it's child's text Uppercase.
here is the source code https://github.com/GeekyAnts/NativeBase/blob/master/src/basic/Button.js
const children =
Platform.OS === PLATFORM.IOS
? this.props.children
: React.Children.map(this.props.children, child =>
child && child.type === Text
? React.cloneElement(child, {
uppercase: this.props.buttonUppercaseAndroidText === false
? false : variables.buttonUppercaseAndroidText,
...child.props
})
: child
);

Text position in React Native

In react native I want to display some texts at some custom positions like in the following image:
custom location react native
How can I achieve this?
I've been playing with the following example:
import React, { Component } from 'react';
import { Text, StyleSheet } from 'react-native';
export default class TextInANest extends Component {
constructor(props) {
super(props);
this.state = {
titleText: "Bird's Nest",
bodyText: 'This is not really a bird nest.'
};
}
render() {
return (
<Text style={styles.baseText}>
<Text style={styles.titleText} onPress={this.onPressTitle}>
{this.state.titleText}{'\n'}{'\n'}
</Text>
<Text numberOfLines={5}>
{this.state.bodyText}
</Text>
</Text>
);
}
}
const styles = StyleSheet.create({
baseText: {
fontFamily: 'Cochin',
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
},
});
trying to set titleText position to absolute and adding some top and leftvalues but it doesn't seem to work.
Any ideas?
From your screenshot, we could say that :
Go to Jane's profile takes 1/11 of the screen height, and is vertically centered
Bird's Nest takes 5/11 of the screen height
This is not... takes 5/11 of the screen height
As in React Native, the main axis is the vertical one (items are positionned below each others by default), you should use justifyContent to vertically centered a Text in a View.
So something like the follow should do the trick.
<View style={{ flex: 1 }}>
<Text>Go to Jane's profile</Text>
</View>
<View style={{ flex: 5, justifyContent: "center" }}>
<Text>Bird's Nest</Text>
</View>
<View style={{ flex: 5 }}>
<Text>This is not...</Text>
</View>
Improved code with working live demo https://snack.expo.io/#akhtarvahid/demo
export default class TextInANest extends React.Component {
constructor(props) {
super(props);
this.state = {
titleText: "Bird's Nest",
bodyText: 'This is not really a bird nest.'
};
}
render() {
return (
<Text style={styles.baseText}>
<Text style={styles.titleText} onPress={this.onPressTitle}>
{this.state.titleText}{'\n'}{'\n'}
</Text>
<Text numberOfLines={5} style={styles.bodyText}>
{this.state.bodyText}
</Text>
</Text>
);
}
}
const styles = StyleSheet.create({
baseText: {
fontFamily: 'Cochin',
},
titleText: {
fontSize: 20,
fontWeight: 'bold'
},
bodyText:{
position:'absolute',
left:10,
top:'50%'
}
});

How to generate background scan line in qrcode scanner

Below is my full code for QRCode scanner
my code is working fine, but i want to add more effects.
Like while scanning one scan moving line in background want to generate, like that moves top to bottom green or red line .
what properties should I add.
please help to add more properties in qrcodescanner.
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TouchableOpacity,
Linking,
View,
Input,
Item,
Button,
AnimationEffect,
ReadableStreamReader,
} from 'react-native';
import { Dimensions } from "react-native";
import QRCodeScanner from 'react-native-qrcode-scanner';
//const SCREEN_HEIGHT = Dimensions.get("window").height;
//const SCREEN_HEIGHT=40;
//const SCREEN_WIDTH=Dimensions.get("window").width;
//const SCREEN_WIDTH=130;
export default class OpenTicket extends Component {
onSuccess(e) {
// console.log(e.data);
this.props.navigation.navigate('OpenApplianceIssue', {
data: e.data,
} );
}
Nextpage() {
// console.log(e.data);
this.props.navigation.navigate('OpenApplianceIssue');
}
onClickListener = () => {
this.props.navigation.navigate('OpenApplianceIssue');
}
static navigationOptions = {
title: 'Open Ticket',
};
render() {
return (
<View style= {{paddingTop:30, paddingBottom:0}}>
// below code is for QRCode scanner
<QRCodeScanner
onRead={this.onSuccess.bind(this)}
cameraProps={{captureAudio: false}}
reactivate = {true}
cameraType={AnimationEffect}
style={ReadableStreamReader}
//cameraStyle={{ height: SCREEN_HEIGHT }}
cameraStyle={{ width: 200, alignSelf:'center'}}
bottomContent={
<Text style={styles.buttonText} onPress={() => this.onClickListener()}>SCAN ITEM{'\n'}
</Text>
}
buttonText={
<Item style={{paddingBottom:10,alignSelf: 'center', justifyContent: 'center', alignItems: 'center'}}>
<Input placeholder='Enter serial number'/>
</Item>
}
/>
<Text>Hello Abhi</Text>
{/* <Item style={{paddingBottom:10,alignSelf: 'center', justifyContent: 'center', alignItems: 'center'}}>
<Input placeholder='Enter serial number'/>
</Item>
<Button full rounded light style={{backgroundColor: 'green', justifyContent: 'center', alignItems: 'center'}}
onPress={() => this.onClickListener()}>
<Text style={{color: 'white'}}>Go</Text>
</Button> */}
</View>
);
}
}
const styles = StyleSheet.create({
centerText: {
flex: 1,
fontSize: 18,
padding: 32,
color: '#777',
},
textBold: {
fontWeight: '500',
color: '#000',
},
buttonText: {
fontSize: 21,
color: 'rgb(0,122,255)',
},
buttonTouchable: {
padding: 16,
},
});
I would give a try to these options for react-native-qrcode-scanner:
showMarker (Use this to show marker on the camera scanning window)
customMarker (Pass a RN element/component to use it as a custom marker)
markerStyle (Use this to add custom styling to the default marker)
UPDATE:
For example, try adding this property to your <QRCodeScanner> element:
showMarker={true}

Styling reusable components in React-Native

I made a reusable component Button.js and I'm importing it on two different screens. The button looks the same, but on the first screen I need it to be position: 'absolute' and on the second one position: 'relative' (the default).
How do I add the position to be absolute on the first screen? I tried to add the styling on FirstPage.js but it does not work. How do I overwrite the style that is defined in Button.js?
Button.js:
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
const Button = ({ position, onPress, children }) => {
const { buttonStyle, textStyle } = styles;
return (
<TouchableOpacity onPress={onPress} style={buttonStyle, {'position': position}}>
<Text style={textStyle}>{children}</Text>
</TouchableOpacity>
);
};
Button.defaultProps = {
position: 'relative',
}
const styles = {
textStyle: {
alignSelf: 'center',
color: '#F44336',
fontSize: 16,
},
buttonStyle: {
zIndex: 2,
width: 100,
backgroundColor: '#FFF',
}
};
export { Button };
You can pass props, something like this (Button.js) (edited according to posted code):
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
const Button = ({ position, onPress, children }) => {
const { buttonStyle, textStyle } = styles;
const style = {...buttonStyle, position };
return (
<TouchableOpacity onPress={onPress} style={style}>
<Text style={textStyle}>{children}</Text>
</TouchableOpacity>
);
};
Button.defaultProps = {
position: 'relative',
}
const styles = {
textStyle: {
alignSelf: 'center',
color: '#F44336',
fontSize: 16,
},
buttonStyle: {
zIndex: 2,
width: 100,
backgroundColor: '#FFF',
}
};
export { Button };
Your button of course looks different, this is just an outline of what you could do (basically just using props).
This is REUSABLE Button as touchableOpacity.
export const NormalThemeButton = (props) => {
return (
<TouchableOpacity
style={[{ ...props.style, ...styles.normalThemeBtn }]}
style={[{ alignItems: props.align }, styles.anchor]}
onPress={props.onPress} >
<CustomText text={props.text} l bold style={{
textAlign: 'center',
color: theme['blackColor']
}} />
{props.children}
</TouchableOpacity >
);
};
This is where this RESUABLE Button is been used.
style={{ ...styles.openArrivedButton }}
text={Lng.instance.translate('useWaze')}
onPress={() => { Waze() }}/>
Hope You find it helpful.

How to change background color of react native button

I am trying to change the background color of my button but nothing seems to work, I tried the raised property, maybe i am using it incorrectly. Do any of you have any ideas?
import React from 'react';
import { StyleSheet, Text, View, Button, TouchableHighlight } from 'react-native';
export default class App extends React.Component {
state={
name: "Mamadou"
};
myPress = () => {
this.setState({
name: "Coulibaly"
});
};
render() {
return (
<View style={styles.container}>
<Button
title={this.state.name}
color="red"
onPress={this.myPress}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Use this for adding the background color to the button in iOS:
Styles:
loginScreenButton:{
marginRight:40,
marginLeft:40,
marginTop:10,
paddingTop:10,
paddingBottom:10,
backgroundColor:'#1E6738',
borderRadius:10,
borderWidth: 1,
borderColor: '#fff'
},
loginText:{
color:'#fff',
textAlign:'center',
paddingLeft : 10,
paddingRight : 10
}
Button:
<TouchableOpacity
style={styles.loginScreenButton}
onPress={() => navigate('HomeScreen')}
underlayColor='#fff'>
<Text style={styles.loginText}>Login</Text>
</TouchableOpacity>
For Android it simply works with Button color property only:
<Button onPress={onPressAction} title="Login" color="#1E6738" accessibilityLabel="Learn more about this button" />
I suggest to use React Native Elements package, which allow to insert styles throught buttonStyle property.
styles:
const styles = StyleSheet.create({
container: {
flex: 1
},
button: {
backgroundColor: '#00aeef',
borderColor: 'red',
borderWidth: 5,
borderRadius: 15
}
})
render()
render() {
return (
<View style={styles.container}>
<Button
buttonStyle={styles.button}
title="Example"
onPress={() => {}}/>
</View>
)
}
Effect:
Expo Snack: https://snack.expo.io/Bk3zI0u0G
"color" property applies to background only if you're building for android.
Other than that I personally find it easier to manage custom buttons. That is create your own component named button and have it as a view with text. This way its way more manageable and you can import it as easy as Button.
this answer is little bit late, but can be good for anothers.
To solve this problem it is better to use "Text" Component as a Button
fist make a component name it AppButton
function AppButton({children,style,onPress}) {
return (
<TouchableOpacity onPress={onPress}>
<Text
style={[styles.appButton,style]} >
{children}
</Text>
</TouchableOpacity>
);
}
export default AppButton;
then Import it in where that you want to use it
import AppButton from './AppButton';
and with this line you can call your custom Button that actually is a Text which you can customize it.
remember onPress Event have to calling in TouchableOpacity not Text:
<AppButton style={styles.appOk} onPress={()=> visibleFunc(false)} >Ok</AppButton>
Maybe Pressable is what you're looking for; it allows you to add style to a pressable component (like a button).Read more here
Sample code:
import React from 'react';
import { Text, View, StyleSheet, Pressable } from 'react-native';
export default function Button(props) {
const { onPress, title = 'Save' } = props;
return (
<Pressable style={styles.button} onPress={onPress}>
<Text style={styles.text}>{title}</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
backgroundColor: 'black',
},
text: {
fontSize: 16,
lineHeight: 21,
fontWeight: 'bold',
letterSpacing: 0.25,
color: 'white',
},
});
You should use the hex code backgroundColor="#FF0000" instead of color="red". Also please use raised={true} other wise background color is not override.

Categories