React-Native Button style not work - reactjs

Import_this
import {AppRegistry, Text, View, Button, StyleSheet} from 'react-native';
This my React Button code But style not working Hare ...
<Button
onPress={this.onPress.bind(this)}
title={"Go Back"}
style={{color: 'red', marginTop: 10, padding: 10}}
/>
Also I was try by this code
<Button
containerStyle={{padding:10, height:45, overflow:'hidden',
borderRadius:4, backgroundColor: 'white'}}
style={{fontSize: 20, color: 'green'}}
onPress={this.onPress.bind(this)} title={"Go Back"}
> Press me!
</Button>
Update Question:
Also I was try by This way..
<Button
onPress={this.onPress.bind(this)}
title={"Go Back"}
style={styles.buttonStyle}
>ku ka</Button>
Style
const styles = StyleSheet.create({
buttonStyle: {
color: 'red',
marginTop: 20,
padding: 20,
backgroundColor: 'green'
}
});
But No out put:
Screenshot of my phone:-

The React Native Button is very limited in what you can do, see; Button
It does not have a style prop, and you don't set text the "web-way" like <Button>txt</Button> but via the title property <Button title="txt" />
If you want to have more control over the appearance you should use one of the TouchableXXXX' components like TouchableOpacity
They are really easy to use :-)

I had an issue with margin and padding with a Button. I added Button inside a View component and apply your properties to the View.
<View style={{margin:10}}>
<Button
title="Decrypt Data"
color="orange"
accessibilityLabel="Tap to Decrypt Data"
onPress={() => {
Alert.alert('You tapped the Decrypt button!');
}}
/>
</View>

React Native buttons are very limited in the option they provide.You can use TouchableHighlight or TouchableOpacity by styling these element and wrapping your buttons with it like this
<TouchableHighlight
style ={{
height: 40,
width:160,
borderRadius:10,
backgroundColor : "yellow",
marginLeft :50,
marginRight:50,
marginTop :20
}}>
<Button onPress={this._onPressButton}
title="SAVE"
accessibilityLabel="Learn more about this button"
/>
</TouchableHighlight>
You can also use react library for customised button .One nice library is react-native-button (https://www.npmjs.com/package/react-native-button)

If you do not want to create your own button component, a quick and dirty solution is to wrap the button in a view, which allows you to at least apply layout styling.
For example this would create a row of buttons:
<View style={{flexDirection: 'row'}}>
<View style={{flex:1 , marginRight:10}} >
<Button title="Save" onPress={() => {}}></Button>
</View>
<View style={{flex:1}} >
<Button title="Cancel" onPress={() => {}}></Button>
</View>
</View>

Instead of using button . you can use Text in react native and then make in touchable
<TouchableOpacity onPress={this._onPressButton}>
<Text style = {'your custome style'}>
button name
</Text>
</TouchableOpacity >

Style in button will not work, You have to give style to the view.
<View style={styles.styleLoginBtn}>
<Button
color="orange" //button color
onPress={this.onPressButton}
title="Login"
/>
</View>
Give this style to view
const styles = StyleSheet.create({
styleLoginBtn: {
marginTop: 30,
marginLeft: 50,
marginRight: 50,
borderWidth: 2,
borderRadius: 20,
borderColor: "black", //button background/border color
overflow: "hidden",
marginBottom: 10,
},
});

Only learning myself, but wrapping in a View may allow you to add styles around the button.
const Stack = StackNavigator({
Home: {
screen: HomeView,
navigationOptions: {
title: 'Home View'
}
},
CoolView: {
screen: CoolView,
navigationOptions: ({navigation}) => ({
title: 'Cool View',
headerRight: (<View style={{marginRight: 16}}><Button
title="Cool"
onPress={() => alert('cool')}
/></View>
)
})
}
})

Try This one
<TouchableOpacity onPress={() => this._onPressAppoimentButton()} style={styles.Btn}>
<Button title="Order Online" style={styles.Btn} > </Button>
</TouchableOpacity>

You can use Pressable with Text instead of button.
import { StyleSheet, Text, View, Pressable } from 'react-native';
<Pressable style={styles.button} onPress = {() => console.log("button pressed")}>
<Text style={styles.text}>Press me</Text>
</Pressable>
Example Style:
const styles = StyleSheet.create({
button: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
backgroundColor: 'red'
},
text: {
fontSize: 16,
lineHeight: 21,
fontWeight: 'bold',
letterSpacing: 0.25,
color: 'white',
},
});

We can use buttonStyle prop now.
https://react-native-training.github.io/react-native-elements/docs/button.html#buttonstyle

React-native button is very limited, it won't allow styling. use react native elements button or create custom button

button styles does'nt work in react-native, to style your button in react-native easy way is to put it inside the View block like this:
<View
style={styles.buttonStyle}>
<Button
title={"Sign Up"}
color={"#F31801"}/>
</View>
style.buttonStyle be like this:
style.buttonStyle{
marginTop:30,
marginLeft:50,
marginRight:50,
borderWidth:2,
borderRadius:20,
borderColor:'#F31801',
overflow:"hidden",
marginBottom:10,
}
, it will make you able to use designs with buttons

As the answer by #plaul mentions TouchableOpacity, here is an example of how you can use that;
<TouchableOpacity
style={someStyles}
onPress={doSomething}
>
<Text>Press Here</Text>
</TouchableOpacity>
SUGGESTION:
I will recommend using react-native-paper components as they are modified and can be modified much more than react-native components.
To install;
npm install react-native-paper
Then you can simply import them and use.
More details here Here

Wrap the button component inside a view component and change the styles of the view component, it should work. Please refer to the snippet below
<View style={{width: 150, alignSelf: 'center'}}>
<Button onPress={demoFunction} title="clickMe!!" />
</View>

I know this is necro-posting, but I found a real easy way to just add the margin-top and margin-bottom to the button itself without having to build anything else.
When you create the styles, whether inline or by creating an object to pass, you can do this:
var buttonStyle = {
marginTop: "1px",
marginBottom: "1px"
}
It seems that adding the quotes around the value makes it work. I don't know if this is because it's a later version of React versus what was posted two years ago, but I know that it works now.

Related

How do I bring up the button in react native?

I want to show the payment button whenever the checkbox is checked and the page will automatically scroll down to show the button to the user.
Currently, I have written the code to display the payment button, but the user must scroll the page to see the button.
I hope you understand what I mean
<CheckBox
title="..."
textStyle={{
color: "#80d2ff",
fontWeight: "normal",
fontFamily: "iransansx",
}}
fontFamily="iransansx"
checked={check11}
containerStyle={{ backgroundColor: "#0000" }}
onPress={() => {
setCheck11(!check11);
}}
/>
</View>
{check11 && (
<Button
title="پرداخت"
color="#0000"
titleStyle={{
color: "#004568",
fontFamily: "iransansx",
}}
containerStyle={{
borderWidth: 2,
borderColor: "#004568",
borderRadius: 8,
width: "94%",
margin: 6,
backgroundColor: "#ECF9FF",
}}
/>
)}
I would be grateful if you could help me
Please do not rate negative
If someone has asked this question before me and received an answer, please link it
You could do this using hook useRef.
const scrollView = useRef();
const onPress = () => {
// enter your code for show payment button here
...
scrollView.current.scrollToEnd();
}
<ScrollView ref={scrollView}>
<CheckBox onPress={onPress} />
</ScrollView>

In NativeBase, how can I avoid inline styling props of component and write it separately and then pass it

I am just trying to write a clean code and avoid lots thing in same tag. For example: Text and Box component have could have so many styling props, So is there any way I can write it separately and they pass it as a whole object as style.
import { Box, extendTheme, NativeBaseProvider, Progress, Text, View } from 'native-base'
import React, { FC } from 'react'
const TrainingList: FC = () => {
return (
<NativeBaseProvider>
<Box my="2">
<Text fontSize="16" lineHeight="21.8" bold> Annual Training </Text>
<View my="2" >
<Text fontSize="14" lineHeight="19.8"> Due in 2 days (01/12/22) </Text>
<Text fontSize="14" lineHeight="19.8"> 50% complete / 10 hrs left </Text>
</View>
<Progress rounded="12" colorScheme="warning" bg="#D7D7D7" size="sm" value={65} mx={0} />
</Box>
<Box mt="5">
This is Box2
</Box>
</NativeBaseProvider>
)
}
export default TrainingList
In my eyes, the best approach will be to add variants to the NativeBase Text and Box component. It'll keep your code but also you'll be able to share consistent style throughout the codebase.
And if you wanna know HOW? I'm sharing a few resources to follow.
Resource:
Official Docs: First place to go.
Snack: A demo snack to show how to add variants.
Blog: To better understand how to effectively customise NativeBase components.
You can use StyleSheet for that. You can use what you defined under styles on components.
import React from "react";
import { StyleSheet, Text, View } from "react-native";
const App = () => (
<View style={styles.container}>
<Text style={styles.title}>React Native</Text>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 24,
backgroundColor: "#eaeaea"
},
title: {
marginTop: 16,
paddingVertical: 8,
borderWidth: 4,
borderColor: "#20232a",
borderRadius: 6,
backgroundColor: "#61dafb",
color: "#20232a",
textAlign: "center",
fontSize: 30,
fontWeight: "bold"
}
});
export default App;
Yes, that's possible using styled components. You can accept props inside of your styling. Alternatively, I prefer using stylesheets as it's simpler and still keeps your code clean. Ex:
<Box style={styles.boxMain}>
<Text style={styles.textOneStyle}> Annual Training </Text>
<View my="2">
<Text style={styles.textTwoStyle}> Due in 2 days (01/12/22) </Text>
<Text style={styles.textTwoStyle}> 50% complete / 10 hrs left </Text>
</View>
</Box>
);
};
const styles = StyleSheet.create({
textOneStyle: {
fontSize: 16,
lineHeight: 21.8,
fontWeight: "bold"
},
textTwoStyle: {
fontSize: 14,
lineHeight: 19.8,
},
});

React Native: Is there any way to make inline styles having a state to turn out external styles?

How can I combine an external style with an inline style which has a state? I just want to place all styles into the style module.
<View
style={[
styles.buttonAcceptDinamic,
{
backgroundColor: !this.state.micState ? null : 'rgba(255,255,255,.4)',
},
]}>
<Icon
name={this.state.micState ? 'mic-off' : 'mic'}
color="white"
size={30}
/>
</View>;
(React native: How to combine external and inline styles?) This solution has an inline style having no state.
Edited: Code works properly. I just wanted to get rid of inline styling having state because VSCode and Error Lens(VSCode Extension) gives me a warning.
If I understand the question correctly:
<View
style={{
...styles.buttonAcceptDinamic,
backgroundColor: !this.state.micState ? null : 'rgba(255,255,255,.4)',
}}>
</View>
Using the spread operator seems the best way to go.
An example using hooks but achieves the same thing, you had an issue with your syntax:
<Text style={[styles.paragraph, isValid ? {'color': 'red'} : "" ]}>
Expo: https://snack.expo.io/rLwktDEHM
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [isValid, setValid] = React.useState(false);
return (
<View style={styles.container}>
<Text style={[styles.paragraph, isValid ? {'color': 'red'} : "" ]}>
Change code in the editor and watch it change on your phone! Save to get a shareable url.
</Text>
<TouchableOpacity onPress={() => setValid(v => !v)}>
<Text>
Change State
</Text>
</TouchableOpacity>
<Card>
<AssetExample />
</Card>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

Multiple onPress event on a single image component in React Native

I have this picture, and I want to have multiple onPress event for this image.
Example if I touch the head part it will call the function pressHead() and if I touch the chest part it will call the function pressChest().
So far I have tried plotting checkboxes on each part.
import React, { Component } from 'react';
import { View, Image, Alert } from 'react-native';
import { CheckBox } from 'react-native-elements';
export default class Screen extends Component {
pressHead() {
this.setState({checked1: !this.state.checked1})
Alert.alert('Pressed Head', '');
}
pressChest() {
this.setState({checked2: !this.state.checked2})
Alert.alert('Pressed Chest', '');
}
render() {
return (
<View style={{width: 200}}>
<Image
style={{width: 200, resizeMode: 'contain'}}
source={require('../../assets/images/body-diagram.png')}
/>
<CheckBox
containerStyle={{position: 'absolute', top: 22, right: 75, padding: 0}}
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checkedColor='#ff0000'
checked={this.state.checked1}
onPress={() => this.pressHead()}
/>
<CheckBox
containerStyle={{position: 'absolute', top: 70, right: 75, padding: 0}}
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checkedColor='#ff0000'
checked={this.state.checked1}
onPress={() => this.pressChest()}
/>
</View>
);
}
}
This does work. But if I try to use it on a larger device, the position absolute becomes not accurate enough.
Give the constant height for the image and overlay the checkboxes as same above respect to image. Since height is also made constant you don't find any position issues of the checkbox in any screen.
Example :
<View style={{width: 200, height: 600}}>
<Image
style={{width: 200, height: 600 ,resizeMode: 'contain'}}
source={require('../../assets/images/body-diagram.png')}
/>
You can do it by changing your image to <ImageBackground .. /> component after importing it from react-native.
After doing that you can place Touchable things inside of ImageBackground.
Example:
<ImageBackground source={require('../../assets/images/body-diagram.png')} style={{width: 200, height: 600, flexDirection: 'column'}}
<TouchableOpacity onPress={() => alert('first pressed')}>
<Text>First Area</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => alert('second pressed')}>
<Text>Second Area</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => alert('third pressed')}>
<Text>Third Area</Text>
</TouchableOpacity>
<ImageBackground/>

Detect tap on the outside of the View in react native

How to detect tap on the outside of the View(View is a small one width and height are 200). For example, I have a custom View(which is like a modal) and it's visibility is controlled by state. But when clicking outside of it nothing is changed because there is no setState done for that, I need to catch users tap everywhere except inside the modal. How is that possible in React Native?
use a TouchableOpacity around your modal and check it's onPress. Look at this example.
const { opacity, open, scale, children,offset } = this.state;
let containerStyles = [ styles.absolute, styles.container, this.props.containerStyle ];
let backStyle= { flex: 1, opacity, backgroundColor: this.props.overlayBackground };
<View
pointerEvents={open ? 'auto' : 'none'}
style={containerStyles}>
<TouchableOpacity
style={styles.absolute}
disabled={!this.props.closeOnTouchOutside}
onPress={this.close.bind(this)}
activeOpacity={0.75}>
<Animated.View style={backStyle}/>
</TouchableOpacity>
<Animated.View>
{children}
</Animated.View>
</View>
const styles = StyleSheet.create({
absolute: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'transparent'
},
container: {
justifyContent: 'center',
elevation: 10,
}
});
<View
onStartShouldSetResponder={evt => {
evt.persist();
if (this.childrenIds && this.childrenIds.length) {
if (this.childrenIds.includes(evt.target)) {
return;
}
console.log('Tapped outside');
}
}}
>
// popover view - we want the user to be able to tap inside here
<View ref={component => {
this.childrenIds = component._children[0]._children.map(el => el._nativeTag)
}}>
<View>
<Text>Option 1</Text>
<Text>Option 2</Text>
</View>
</View>
// other view - we want the popover to close when this view is tapped
<View>
<Text>
Tapping in this view will trigger the console log, but tapping inside the
view above will not.
</Text>
</View>
</View>
https://www.jaygould.co.uk/2019-05-09-detecting-tap-outside-element-react-native/
I found these solution here, hope it helps
Wrap your view in TouchableOpacity/TouchableHighlight and add onPress Handler so that you can detect the touch outside your view.
Something like :
<TouchableOpacity onPress={() => {console.log('Touch outside view is detected')} }>
<View> Your View Goes Here </View>
</TouchableOpacity>

Resources