Disabling buttons on react native - react-native

I'm making an android app using react native and I've used TouchableOpacity component to create buttons.
I use a text input component to accept text from the user and the button should only be enabled once the text input matches a certain string.
I can think of a way to do this by initially rendering the button without the TouchableOpactiy wrapper and re-rendering with the wrapper once the input string matches.
But I'm guessing there is a much better way to do this. Can anyone help?

TouchableOpacity extends TouchableWithoutFeedback, so you can just use the disabled property :
<TouchableOpacity disabled={true}>
<Text>I'm disabled</Text>
</TouchableOpacity>
React Native TouchableWithoutFeedback #disabled documentation
The new Pressable API has a disabled option too :
<Pressable disabled={true}>
{({ pressed }) => (
<Text>I'm disabled</Text>
)}
</Pressable>

Just do this
<TouchableOpacity activeOpacity={disabled ? 1 : 0.7} onPress={!disabled && onPress}>
<View>
<Text>{text}</Text>
</View>
</TouchableOpacity>

this native-base there is solution:
<Button
block
disabled={!learnedWordsByUser.length}
style={{ marginTop: 10 }}
onPress={learnedWordsByUser.length && () => {
onFlipCardsGenerateNewWords(learnedWordsByUser)
onFlipCardsBtnPress()
}}
>
<Text>Let's Review</Text>
</Button>

So it is very easy to disable any button in react native
<TouchableOpacity disabled={true}>
<Text>
This is disabled button
</Text>
</TouchableOpacity>
disabled is a prop in react native and when you set its value to "true" it will disable your button
Happy Cooding

This seems like the kind of thing that could be solved using a Higher Order Component. I could be wrong though because I'm struggling to understand it 100% myself, but maybe it'll be helpful to you (here's a couple links)...
http://www.bennadel.com/blog/2888-experimenting-with-higher-order-components-in-reactjs.htm
http://jamesknelson.com/structuring-react-applications-higher-order-components/

TouchableOpacity receives activeOpacity. You can do something like this
<TouchableOpacity activeOpacity={enabled ? 0.5 : 1}>
</TouchableOpacity>
So if it's enabled, it will look normal, otherwise, it will look just like touchablewithoutfeedback.

To disable Text you have to set the opacity:0 in Text style like this:
<TouchableOpacity style={{opacity:0}}>
<Text>I'm disabled</Text>
</TouchableOpacity>

You can use the disabled prop in TouchableOpacity when your input does not match the string
<TouchableOpacity disabled = { stringMatched ? false : true }>
<Text>Some Text</Text>
</TouchableOpacity>
where stringMatched is a state.

You can build an CustButton with TouchableWithoutFeedback, and set the effect and logic you want with onPressIn, onPressout or other props.

I was able to fix this by putting a conditional in the style property.
const startQuizDisabled = () => props.deck.cards.length === 0;
<TouchableOpacity
style={startQuizDisabled() ? styles.androidStartQuizDisable : styles.androidStartQuiz}
onPress={startQuiz}
disabled={startQuizDisabled()}
>
<Text
style={styles.androidStartQuizBtn}
>Start Quiz</Text>
</TouchableOpacity>
const styles = StyleSheet.create({
androidStartQuiz: {
marginTop:25,
backgroundColor: "green",
padding: 10,
borderRadius: 5,
borderWidth: 1
},
androidStartQuizDisable: {
marginTop:25,
backgroundColor: "green",
padding: 10,
borderRadius: 5,
borderWidth: 1,
opacity: 0.4
},
androidStartQuizBtn: {
color: "white",
fontSize: 24
}
})

I think the most efficient way is to wrap the touchableOpacity with a view and add the prop pointerEvents with a style condition.
<View style={this.state.disabled && commonStyles.buttonDisabled}
pointerEvents={this.state.disabled ? "none" : "auto"}>
<TouchableOpacity
style={styles.connectButton}>
<Text style={styles.connectButtonText}">CONNECT </Text>
</TouchableOpacity>
</View>
CSS:
buttonDisabled: {
opacity: 0.7
}

Here's my work around for this I hope it helps :
<TouchableOpacity
onPress={() => {
this.onSubmit()
}}
disabled={this.state.validity}
style={this.state.validity ?
SignUpStyleSheet.inputStyle :
[SignUpStyleSheet.inputAndButton, {opacity: 0.5}]}>
<Text style={SignUpStyleSheet.buttonsText}>Sign-Up</Text>
</TouchableOpacity>
in SignUpStyleSheet.inputStyle holds the style for the button when it disabled or not, then in style={this.state.validity ? SignUpStyleSheet.inputStyle : [SignUpStyleSheet.inputAndButton, {opacity: 0.5}]} I add the opacity property if the button is disabled.

You can enable and disable button or by using condition or directly by default it will be disable : true
// in calling function of button
handledisableenable()
{
// set the state for disabling or enabling the button
if(ifSomeConditionReturnsTrue)
{
this.setState({ Isbuttonenable : true })
}
else
{
this.setState({ Isbuttonenable : false})
}
}
<TouchableOpacity onPress ={this.handledisableenable} disabled=
{this.state.Isbuttonenable}>
<Text> Button </Text>
</TouchableOpacity>

Use disabled true property
<TouchableOpacity disabled={true}> </TouchableOpacity>

Here is the simplest solution ever:
You can add onPressOut event to the TouchableOpcaity
and do whatever you want to do.
It will not let user to press again until onPressOut is done

Related

Vertically align Pressable inside a Text component

<View
style={{
flexDirection: "row",
}}
>
<Text
style={{
flex: 1,
}}
>
By continuing, you agree to our{" "}
<Pressable
onPress={...}
>
<Text>
Terms of Service
</Text>
</Pressable>
</Text>
</View>
"Terms of Service" is printed higher than "By continuing, you agree to our". How do I vertically align them?
Or more precisely - how do I get the Pressable Text to vertically align to the bottom?
This is a bug in React Native itself. There are several open reports of this bug on React Native's GitHub, but the chances of it being fixed don't look good:
https://github.com/facebook/react-native/issues/30375 - for the general problem of Views nested in Text being mis-aligned on Android, and a core contributor responded, but appeared to get derailed and stuck in some details specific to mimicking superscript and subscript.
https://github.com/facebook/react-native/issues/31955 - specific to Pressable and someone posted a PR to fix it, but Facebook closed it because no-one from Facebook got around to reviewing it before it became stale and out of date with the main branch.
There's also some discussion in this issue comment, but the issue got closed.
In React Native >= 0.65, if your inline pressable element uses only text styles, you can work around this issue by using <Text> with onPress (and onPressIn and onPressOut to style the pressed state). Crude example:
/**
* Like a simplified Pressable that doesn't look broken inline in `Text` on Android
*/
const TextButton = ({ children, onPress, style, ...rest } => {
const [pressed, setPressed] = useState(false)
const onPressIn = () => setPressed(true)
const onPressOut = () => setPressed(false)
return (
<Text
onPress={onPress}
onPressIn={onPressIn}
onPressOut={onPressOut}
style={typeof style === 'function' ? style({ pressed }) : style}
{...rest}
>
{typeof children === 'function' ? children({ pressed }) : children}
</Text>
)
}
Beware, however, that there are also bugs around selecting interactive elements nested inside text using accessibility tools. If you can simply avoid nesting the interactive element in text, and have it on its own line, that's probably better: link-like interactive nested text isn't well supported in React Native currently.
On older versions of React Native before 0.65, Text didn't support onPressIn or onPressOut:
If you don't need Pressable's pressed state, use Text instead of Pressable (as the asker did: https://stackoverflow.com/a/66590787/568458)
If you do need pressed state, Text doesn't support the required onPressIn/Out handlers. However, TouchableWithoutFeedback does support those, and works by injecting props into its child so the Text will remain Text with no wrapping View. Wrap a Text in TouchableWithoutFeedback and pass the touchable onPress with onPressIn and onPressOut handlers and store the pressed state yourself.
/**
* Like a simplified Pressable that doesn't look broken inline in `Text` on Android
*/
const TextButton = ({ children, onPress, style, ...rest } => {
const [pressed, setPressed] = useState(false)
const onPressIn = () => setPressed(true)
const onPressOut = () => setPressed(false)
// TouchableWithoutFeedback modifies and returns its child; this returns `Text`
// plus press in/out events attached that aren't supported by Text directly.
return (
<TouchableWithoutFeedback
onPress={onPress}
onPressIn={onPressIn}
onPressOut={onPressOut}
>
<Text
style={typeof style === 'function' ? style({ pressed }) : style}
{...rest}
>
{typeof children === 'function' ? children({ pressed }) : children}
</Text>
</TouchableWithoutFeedback>
)
}
Warning: if you're also using React Native Web and React Navigation, don't use the TouchableWithoutFeedback approach on Web, use pure Pressable on web, because React Navigation's navigate functions don't reliably work when passed to Touchable*s on Web due to a quirk of how the event handlers are set up (but they do work in Pressable), and this issue doesn't exist on Web.
Ended up doing this differently, using the onPress property of the <Text> component and finally wrapping all <Text> components in another <Text> component to have a proper line break:
<View>
<Text>
<Text>
By continuing, you agree to our{" "}
</Text>
<Text onPress={() => {...}}>
Terms of Service
</Text>
<Text>
{" "}and our{" "}
</Text>
<Text onPress={() => {...}}>
Privacy Policy
</Text>
</Text>
</View>
The snippet below should work but hard to understand without giving a shot. If you can provide screenshots I can help more in sake of getting a more proper result.
<View>
<Text style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
}}>
By continuing, you agree to our{" "}
<Pressable
onPress={() => {
navigate("LegalStack", { screen: "Terms" });
}}
>
<Text style={{margin: 'auto'}}>
Terms of Service
</Text>
</Pressable>
</Text>
</View>
I found a very hackidy-hack solution...
<Text selectable={true}>
<Text>if you click</Text>
<TouchableOpacity
style={{flexDirection: 'row'}}
onPress={() => Linking.openURL("https://www.google.com")}
>
<Text
style={{
alignSelf: 'flex-end',
marginBottom: -4,
}}
>
here
</Text>
</TouchableOpacity>
<Text>, it will open google</Text>
</Text>
By default the flexDirection is column. Change it to flexDirection:"row"

How to change Opacity of button in conditional rendering in react native

I am new to react native. I have created a form. in which I am rendering some buttons according to server response. Now I want to set opacity of button 50% means. I want that button should look like its a disabled Now. SO is it possible if yes then please help. thanks. I want to set that opacity in my 1st line of code
here is my code
{data.bank_account_details_data[0] != null && (
<TouchableOpacity>
<Card center middle shadow style={styles.category} >
OTHER INFORMATION
</Text>
</Card>
</TouchableOpacity>
)}
You can set the opacity of the TouchableOpacity with a ternary expression (like your first line) based on a condition within the style prop.
Simplified example:
export default function App() {
const [hasOpacity, setHasOpacity] = React.useState(false)
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => {
setHasOpacity(!hasOpacity)
}}
activeOpacity={0.2}
style={{opacity: hasOpacity ? 0.5 : 1.0}}
>
<Text>Test</Text></TouchableOpacity>
</View>
);
}
https://snack.expo.io/a1Y-TU4XB
In your example, it might look like this:
<TouchableOpacity
activeOpacity={0.2}
style={{opacity: data.bank_account_details_data[0] != null ? 0.5 : 1.0}}
>
you can use something like this
<TouchableOpacity
// opacity value ranges from 0 to 1
activeOpacity={0.9} //opacity for on touch behaviour
style={{opacity:0.9}} // opacity for view behaviour
onPress={()=>{
console.log("i am here")
}}>
<Text style={{color:"#FFF"}}>This is opacity check</Text>
</TouchableOpacity>
instead of static value of opacity you can use state, props or value from backend as a variable as well

React Native Button: Fit to text layout

In the Button docs from React-Native here it shows an image which says: Fit to text layout. That is what I am searching for because my button always has full width, but I want it to only be as wide as the text is. But neither in the docs nor in the button code here I can find something related to that a prop or how can it achieve. Somebody has an idea how to get it?
I suggest making your own button with TouchableOpacity and Text.
For example this is my component I often use :
export default class RoundedButton extends React.Component<Props>{
render(){
const defStyles : StyleProp<ViewStyle> = [style.button, {
backgroundColor: this.props.backgroundColor,
}, this.props.style];
if(this.props.shadow)
defStyles.push(style.shadow);
return(
<TouchableOpacity
disabled={!this.props.onPress}
onPress={() => {
if(this.props.onPress)
this.props.onPress();
}}
style={defStyles}
>
<Text style={{
color: this.props.textColor,
fontFamily: fonts.bold,
fontSize: 16
}}>{this.props.centerText}</Text>
</TouchableOpacity>
);
}
}
You can found the full gist here if you want : https://gist.github.com/Sangrene/176c1b87ad5b355e26b5c6aa80b96eae.
You can pass the prop adjustsFontSizeToFit={true} in your Text component.
If you add a fontSize in the styles of the Text, it will override this prop and won't work.
Example
<View style={{widht: 100, height: 60}}>
<Text adjustsFontSizeToFit={true}>
Your Text Here
</Text>
</View>

this.refs.FieldName.focus() is not a function in React Native

I am using Custom Keyboard. In that I am using CustomTextInput in place of TextInput. All works well but I want to focus input field in function.
<CustomTextInput customKeyboardType="hello"
onFocus={() => this.onFocus('fieldname')}
selectTextOnFocus={ true }
ref="TextInput"
underlineColorAndroid = 'transparent'
onChangeText={(value) => this.setState({fieldname:this.onChange(value)})}
/>
In Function something like below :-
function () {
Keyboard.dismiss();
this.refs.TextInput.focus();
}
But I am getting an error :- this.refs.TextInput.focus is not a function.
Basically my focus() function is not working.
Please help!
I tried this.refs['TextInput'].focus() and it works for me. You can write a function for Textinput's onFocus and within this function dimiss default keyboard, lunch your customized keyboard and focus again on your TextInput. I hope it will help.
This is my code:
<TextInput
style={{ height: 40, width: 200 }}
ref="TextInput"
/>
<TouchableOpacity
onPress={() => { (this.refs['TextInput'] as any).focus() }}>
<Text>Press to focus</Text>
</TouchableOpacity>

React native textinput multiline is not being pushed up by keyboard

I have a TextInput with multiLine true. However, after two lines the text disappear behind the keyboard. I have tried wrapping the TextInput in KeyboardAvoidingView, but it doesn't work.
The keyboard does push up the TextInput when I unfocus the TextInput and then click on the bottom line. Any idea how I can make the last line of the TextInput stay on top of the keyboard?
The code:
<View style={styles.descriptionFlexStyle}>
<Text
style={[
styles.headerTextStyle,
{ marginTop: Window.height * 0.04 }
]}> Please fill in a reason </Text>
<ScrollView>
<TextInput
style={styles.reasonTextInput}
placeholder="Reason"
value={reasonText}
multiline={true}
onChangeText={input =>
this.setState({
reasonText: input
})
}
underlineColorAndroid="transparent"
ref="reasonTextInput"
/>
</ScrollView>
</View>
hello my dear you must use KeyboardAvoidingView Component from React-Native and put a behavior on it like below :
<KeyboardAvoidingView behavior={'postion' || 'height' || 'padding'}>
<View style={styles.descriptionFlexStyle}>
<Text
style={[
styles.headerTextStyle,
{ marginTop: Window.height * 0.04 }
]}> Please fill in a reason </Text>
<ScrollView>
<TextInput
style={styles.reasonTextInput}
placeholder="Reason"
value={reasonText}
multiline={true}
onChangeText={input =>
this.setState({
reasonText: input
})
}
underlineColorAndroid="transparent"
ref="reasonTextInput"
/>
</ScrollView>
</View>
</KeyboardAvoidingView>
This answer may be a little too late. However, I have found a workaround without using the KeyboardAvoidingView component. A ScrollView could be used instead to scroll the multiline TextInput to the top to have the 'keyboard avoiding' effect. I would use the ref measure() method to get the top y value of the TextInput, before using the scrollTo() method to scroll the TextInput directly to the top of the screen, effectively avoiding the keyboard.
import React, { useRef } from "react";
import { ScrollView, TextInput, View } from "react-native";
export default function Test() {
const scrollViewRef = useRef(null);
const viewRef = useRef(null);
const handleFocus = () => {
viewRef.current.measure((x, y) => {
scrollViewRef.current.scrollTo({ x: 0, y });
});
};
return (
<ScrollView ref={scrollViewRef}>
{/* View to fill up space */}
<View
style={{
width: "80%",
height: 600,
}}
/>
<View ref={viewRef}>
<TextInput
onFocus={handleFocus}
multiline={true}
style={{
width: "80%",
height: 100,
backgroundColor: "whitesmoke",
alignSelf: "center",
}}
/>
{/* View to fill up space */}
<View
style={{
width: "80%",
height: 600,
}}
/>
</View>
</ScrollView>
);
}
Ok i have finally solved it using "KeyboardAvoidingView". I did two things. First i removed the height on my TextInput and then i set the behavior attribute on the "KeyboardAvoidingView" to "padding". Works perfect for me now. Let me know if this help! :)