Style object is not applied in Component - javascript

I have this Component
import React from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
const styles = StyleSheet.create({
container: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
width: 50,
height: 50,
borderRadius: 25,
},
button: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
borderRadius: 20,
height: 40,
width: 40,
},
});
const Button = ({
children = 'NO CONTENT HERE',
color = 'red',
onPress,
style = {},
}) => {
return <View
style={styles.container}>
<TouchableOpacity
style={[{ backgroundColor: color }, styles.button, style]}
onPress={onPress}>
{children}
</TouchableOpacity>
</View>
}
Button.propTypes = {
color: PropTypes.string,
onPress: PropTypes.func,
style: PropTypes.object
}
export default Button;
I use the Component <Button /> and do not pass a color prop to it. I expect the <Button /> to become red. However, it is white. When I pass a color prop, lets say green, it does not work neither. However, when I add a backgroundColor to the StyleSheet.button it gets applied. Why is that?

You need to change the order in which you apply the styles.
Try changing it to
<TouchableOpacity
style={[styles.button, style, { backgroundColor: color }]}
onPress={onPress}>
When you pass in multiple values with the same key, the last value is the one that gets used.

In React-Native, color props for Button works based on the mobile platform whether it’s an iOS or Android. When we pass color prop to a button, it changes the text color in iOS and a background-color in Android. So, it’s better to not rely on this prop for your requirement.
You may check the official React-Native documentation for button here-
https://reactnative.dev/docs/button
I would suggest to use a separate class to apply color to the button.

Related

How to change the style with props

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>
)
}

React Native Paper ProgressBar Not visible

Hello i was following along a tutorial and it was going fine, until the tutor used react-native-paper ProgressBar in his project, I wrote exactly same but it was not visible, I found the documentation and plugged it, still not visible.
What am i Doing wrong?
import {View, StyleSheet, Text} from 'react-native' ;
import { ProgressBar, Colors } from 'react-native-paper';
import CountDown from '../comps/CountDown.js' ;
const Timer = ({task}) => {
return (
<View style={styles.container}>
<CountDown />
<Text style={styles.text}> Focusing On:</Text>
<Text style={[styles.text, styles.textBold]}> {task} </Text>
<ProgressBar progress={0.4} color='#5E84E2' style={styles.progress}/>
</View>
) ;
}
const styles = StyleSheet.create({
container : {
flex: 1,
width: 100,
alignItems: 'center' ,
justifyContent: 'center',
paddingTop: 40,
},
text: {
// flex: 0.5,
color: 'white'
},
textBold: {
fontWeight: 'bold' ,
// borderColor: 'white',
// borderWidth: 1,
// borderStyle: 'solid' ,
},
progress: {
height: 10,
// borderColor: 'white',
// borderWidth: 1,
// borderStyle: 'solid' ,
}
}) ;
export default Timer ;
Also, If i were to Give border to the progressBar, it appears but keep on increasing in width even when width is more than the viewport width. I dont know what is happening
The problem here is when you use alignItems the children components need to have a fixed width, your progress bar doesnet have a fixed width.
You will have to provide a with in the styles.
progress: {
height: 10,
width:50
}
Based on documentation default value for width is
auto (default value) React Native calculates the width/height for the
element based on its content, whether that is other children, text, or
an image.
Better have a value for width which will solve your issue.
A responsive solution
Currently ProgressBar doesn't support the flex styling system.
If someone is also looking to make the width equal to 100% if it's parrent component, there is a good recommended solution provided here.
Just set the width to undefined:
progress: {
height: 10,
width:undefined
}
e.g.
<View style={{ flex: 2, other flex styles }}>
<ProgressBar progress={0.5} color="white" style={{ height: 5, width: undefined }} />
</View>

Flex header layout in React Native

I'm new here on react native, And i was trying to align the back button to the left, But keeping the title on the center, But nothing works, This is the code.
The TouchableOpacity is the back button, And the Text is the title, Each one have his own style.
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Image } from 'react-native';
import { Colors } from '../Variables';
class Header extends Component {
render(){
return(
<View style={ styles.headerStyle }>
<TouchableOpacity>
<Image style={ styles.backBtnStyle } source={ require('../graphics/icons/arrow_left_white.png') }/>
</TouchableOpacity>
<Text style={ styles.titleStyle }>
TITLE
</Text>
</View>
);
}
}
const styles = {
headerStyle: {
backgroundColor: Colors.primary,
flexDirection: 'row',
alignItems: 'center',
},
backBtnStyle: {
width: 25,
height: 25,
margin: 10,
},
titleStyle: {
color: '#fff',
textAlign: 'center',
fontSize: 25,
}
};
export default Header;
Thanks for helping.
You should try to view this document about Flex in React native and practive more to mastered it.
In Your case, just simplify add alignSelf: 'flex-start' to backBtnStyle StyleSheet to make it in first of your parent component
Here is demo code:
headerStyle: {
backgroundColor: Colors.primary,
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'flex-start'
},
<TouchableOpacity style={styles.backBtnStyle}>
<Image source={require('../graphics/icons/arrow_left_white.png') }/>
</TouchableOpacity>
You see: TouchableOpacity contain a Viewable Layout and wrap your image then you need to set style for TouchableOpacity to make flex work, not at Image.
From React NativeTouchableOpacity Documents: Opacity is controlled by wrapping the children in an Animated.View, which is added to the view hierarchy. Be aware that this can affect layout.
You can see Touchable Opacity Document here
Note: Set Your StyleSheet on StyleSheet.create() to make it create one and only one time when your bundle load. It make your app light weight and faster
Read about React Native StyleSheet here
You are using alignItems: 'center' in your container, so everything will be in the center.
In your case, there are a lot of solutions available. The more simple is just use a position: absolute; left: 15 in the styles.backBtnStyle.

How to change button color when pressed in React Native using TouchableHighlight?

I am currently developing an application, and I am having trouble figuring out how to get the button to change color after being pressed using TouchableHighlight. Not to be confused with the underlayColor prop which I know exists as part of TouchableHighlight which only changes the color for when the button is pressed and then returns to its regular color.
This is what I have so far (Some of the code has been omitted for simplicity):
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight,
Alert,
} from 'react-native';
class MeetingScreen extends Component {
constructor(props){
super(props);
this.state = {
buttonColor: '#7395AE',
}
this.onButtonPress=this.onButtonPress.bind(this);
}
onButtonPress(){
this.setState({ buttonColor: 'red' });
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
style={styles.talk}
color={this.state.buttonColor}
onPress={() => this.state.buttonColor}
selected={this.onButtonPress}
>
<View>
<Text style={styles.welcome} >
Talk
</Text>
</View>
</TouchableHighlight>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#7395AE',
},
welcome: {
fontSize: 30,
textAlign: 'center',
margin: 10,
color: '#ffffff',
},
talk:{
height: 200,
width: 200,
borderWidth: 5,
backgroundColor: '#7395AE',
borderRadius: 100,
borderColor: '#557A95',
justifyContent:'center',
alignItems:'center',
borderRadius: 100
},
});
export default connect(mapStoreToProps, mapDispatchToProps)(MeetingScreen);
I have looked at other answers on StackOverflow and have attempted a good portion of them but I couldn't find anything that fit specifically to my issue. I have also looked at the React Native documentation and wasn't able to find anything helpful. The code as it is right now just displays the button and when pressed it goes black but then goes back to it's original color after being pressed. What I am looking for is for the button to turn red and stay red after being pressed. Any help would be greatly appreciated. Thank you so much for any help in advance!
<TouchableHighlight
style={[styles.talk, { backgroundColor: this.state.buttonColor}]} //Or if don't want "backgroundColor:" and just need change the text color use => "color:""
onPress={() => this.state.buttonColor}
selected={this.onButtonPress}/>

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