how do I enable/disable textinput programmatically in expo? - javascript

the problem is that I am trying enable/disable fields in a form with the use of a
I have tried following the steps in this tutorial
https://dev.to/skptricks/react-native-enable-and-disable-textinput-programmatically-1b99
Here is where I have got to so far
onPressButton = () => {
this.setState({ TextInputDisableStatus: false })
}
<TextInput
label="Name"
placeholder="Colin Molony"
autoCapitalize="none"
keyboardType="default"
keyboardAppearance="default"
returnKeyType="next"
returnKeyLabel="Next"
blurOnSubmit={false}
selectTextOnFocus={true}
style={styles.textInput}
editable={this.state.TextInputDisableHolder}
/>
ProfileScreen.navigationOptions = {
title: 'Profile Page',
headerRight: (
<Ionicons
style={{padding: 15}}
name={Platform.OS === 'ios' ? 'ios-create' : 'md-create'}
size={26}
onPress={this.onPressButton}
/>
),
};
When I click the icon I get the following error this.setstate is not a function

I think there is a naming problem. I followed your link and the author there initializes the following state:
constructor() {
super();
this.state = { TextInputDisableStatus: true }
}
In the onPress method, you are updating the status with:
onPressButton = () => {
this.setState({ TextInputDisableStatus: false })
}
But then inside the TextInput the author and you are referring to
editable={this.state.TextInputDisableHolder}
this should probably be changed to:
editable={this.state.TextInputDisableStatus}
In addition you have to change:
onPressButton() {
this.setState({ TextInputDisableStatus: false })
}
and:
<Ionicons
style={{padding: 15}}
name={Platform.OS === 'ios' ? 'ios-create' : 'md-create'}
size={26}
onPress={() => this.onPressButton()}
/>

Related

custom checkbox false or true after click

I'm developing a Checkbox component, because the native one doesn't work because of Expo, so I decided to create a custom one, but I'm new to react native and I'm not able to change the state of my component after the click, what I need is that after the click, the box is unchecked, and if I click again, the box is checked again, but this only happens when the checked property is true. How do I change from true to false after the click?
Index.tsx
export interface Properties {
newColor?: Boolean;
id?: String;
checked?: Boolean;
onChange?: () => void;
label?: String;
}
const Checkbox: React.FC<Properties> = (props: Properties) => {
const config: Config = {
types: [
{
title: "",
isDefault: true,
},
"",
],
modifiers: ["inverse"],
states: ["disable"],
};
return (
<>
<View>
<TouchableOpacity
{...props}
onPress={() => handleClick()}
style={styles.container}
>
<View
style={styles.checkboxUnchecked}
>
{props.checked === true ? (
<View
style={styles.checkboxChecked}
>
<Icon
name={"check"}
/>
</View>
) : (
<View
style={styles.checkboxUnchecked}
>
</View>
)}
</View>
{
<Text>
{props.label}
</Text>
}
</TouchableOpacity>
</View>
</>
);
};
To use the component I call it this
<Checkbox checked={false} label={"Label"} id={"i3"}/>
but the result i have is:
but if I call the component this way I get another result
<Checkbox checked={true} label={"Label"} id={"i3"}/>
Use react state
Your code should be like this.
const Checkbox: React.FC<Properties> = (props: Properties) => {
const [value, setValue] = React.useState(props.checked /*default value*/);
const handleClick = () => {
const newValue = !value; //switch value
setValue(newValue);
if(props.onChange) props.onChange(newValue);
}
return(
<TouchableOpacity onPress={() => handleClick()}>
{value === true && <View style={styles.checkboxChecked}></View>}
{value === false && <View style={styles.checkboxUnchecked}></View>}
</TouchableOpacity>
)
}
use it like this
<Checkbox
checked={true} //defaultvalue
onChange={value => alert("new value is: " + value)} //handle new value
/>

React Native, values are not updating

I made a edit screen and trying to update the value of post through navigation v4 by using getParams and set setParams but when I change the old value and click save buttton to save it, it's not updating it and no error is showing either. It's still showing old values. Can someone please help me, below is my code
EditScreen.js
class EditScreen extends Component {
render() {
const { params } = this.props.navigation.state;
return (
<KeyboardAvoidingView
behavior="position"
keyboardVerticalOffset={Platform.OS === "ios" ? 0 : 100}
>
<Image
style={styles.image}
source={this.props.navigation.getParam("image")}
/>
<View style={styles.detailContainer}>
<AppTextInput
value={this.props.navigation.getParam("title")}
onChangeText={(text) =>
this.props.navigation.setParams({ title: text })
}
/>
<AppTextInput
value={this.props.navigation.getParam("des")}
onChangeText={(text) =>
this.props.navigation.setParams({ des: text })
}
/>
</View>
<AppButton
text="Save"
style={styles.button}
onPress={() => {
this.props.navigation.getParam("onEdit");
this.props.navigation.goBack();
}}
/>
</KeyboardAvoidingView>
Home.js
class Home extends Component {
state = {
modal: false,
post: [
{
key: "1",
title: "A Good Boi",
des: "He's a good boi and every one know it.",
image: require("../assets/dog.jpg"),
},
{
key: "2",
title: "John Cena",
des: "As you can see, You can't see me!",
image: require("../assets/cena.jpg"),
},
],
};
onEdit = (data) => {
const newPosts = this.state.post.map((item) => {
if (item.key === data.key) return data;
else return item;
});
this.setState({ post: newPosts, editMode: false });
};
render() {
return (
<Screen style={styles.screen}>
<FlatList
data={this.state.post}
renderItem={({ item }) => (
<>
<TouchableOpacity
activeOpacity={0.7}
onPress={() =>
this.props.navigation.navigate("Edit", {
image: item.image,
title: item.title,
des: item.des,
onEdit: this.onEdit,
})
}
style={styles.Edit}
>
<MaterialCommunityIcons
name="playlist-edit"
color="green"
size={35}
/>
</TouchableOpacity>
<Card onPress={() => this.props.navigation.push("Details", item)}>
<Image style={styles.image} source={item.image} />
<View style={styles.detailContainer}>
<Text style={styles.title} numberOfLines={1}>
{item.title}
</Text>
<Text style={styles.subTitle} numberOfLines={2}>
{item.des}
</Text>
</View>
</Card>
</>
I recommend you to keep the data in the component state:
constructor(props) {
super(props);
// get the data that you need from navigation params
const { key, title, ..} = this.props.navigation.state.params
this.state = {key, title, ..}
}
then :
<AppTextInput
value={this.state.title}
onChangeText={(text) =>
this.setState({ title: text })
}
/>
<AppButton
text="Save"
style={styles.button}
onPress={() => {
this.props.navigation.getParam("onEdit")(this.state);
this.props.navigation.goBack();
}}
/>
Maybe try this:
<AppButton
text="Save"
style={styles.button}
onPress={() => {
this.props.navigation.getParam("onEdit")(this.props.navigation.state.params);
this.props.navigation.goBack();
}}
/>
and:
this.props.navigation.navigate("Edit", {
key: item.key,
image: item.image,
title: item.title,
des: item.des,
onEdit: this.onEdit,
})

Focus text input on TouchableHighlight clicked

I have a class that I want the text input inside it to focus on the parent being selected.
class ListItem extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
editable: this.props.item.editable,
value: this.props.item.value,
heading: this.props.item.heading,
item: this.props.item.item,
}
}
_onPress = () => {
this.setState({ editable: true});
this.props.onPressItem(this.props.index, this.props, this.state);
}
_onSearchTextChanged = (event) => {
this.setState({ value: event.nativeEvent.text });
};
_handleSaveEvent = (e) => {
this.setState({ editable: false });
alert('works');
//Add in saving item
}
render() {
var editable = this.state.editable;
var heading = this.state.heading;
var value = this.state.value;
return (
<TouchableHighlight onPress={this._onPress} underlayColor='#dddddd'>
<View>
<View style={styles.rowContainer}>
<View style={styles.textContainer}>
<Text style={styles.title}>{heading}: </Text>
{this.state.editable?
<TextInput
style={styles.searchInput}
value={value.toString()}
onChange={this._onSearchTextChanged}
keyboardType="default"
returnKeyType="done"
onSubmitEditing={this._handleSaveEvent}/>
:
<Text style={styles.price}>{value}</Text>
}
{}
</View>
</View>
<View style={styles.separator}/>
</View>
</TouchableHighlight>
);
}
}
Ive tried adding
autoFocus={true}
Ive also tried adding
ref={this.props.index}
But when I try to focus that it tells me its not defined (this.refs[this.props.index].focus();)
I would like it to be focused when the 'editable' state is enabled, I am not sure why this seems so hard. My background is more in C#, Angular 2+ etc so maybe its just how react is structured is throwing me
on the onPress event of TouchableHighlight setState editable: true and set autoFocus={this.state.editable} in TextInput..it will work
<TextInput
style={styles.searchInput}
value={value.toString()}
onChange={this._onSearchTextChanged}
keyboardType="default"
autoFocus={this.state.editable}
returnKeyType="done"
onSubmitEditing={this._handleSaveEvent}
/>
You can try this. Provide ref as a function in <TextInput /> like this:
<TextInput
ref ={ref => this.inputText = ref}
style={styles.searchInput}
keyboardType="default"
placeholder="Type anything"
returnKeyType="done"/>
And now on <Button />onPress, focus the <TextInput /> like this:
<TouchableHighlight onPress={() => this.inputText.focus()}>
<Text>Click</Text>
</TouchableHightlight>
This should work. Let me know if there is any problem.

React Native - React Navigation Tab Bar - Custom floating action button

I need some help to use React Native - react navigation library.
It is Tab bar, but the Upload button acted as floating action button.
I have try :
const click = () => {
console.log('click');
return (
<View>
<Text>a</Text>
</View>
);
};
tabBarOnPress: (tab) => {
click();
},
// Main Page Navigator
export const Main = TabNavigator({
Home: {
screen: HomeNavigator,
},
Explore: {
screen: ExploreNavigator,
},
Upload: {
screen: UploadMain,
navigationOptions: ({ navigation }) => ({
tabBarLabel: 'Upload',
tabBarIcon: ({ tintColor }) => (
<View>
<Icon name="camera" size={26} color={tintColor} />
</View>
),
tabBarOnPress: (tab) => {
click();
},
}),
},
}, {
tabBarComponent: TabBarBottom,
tabBarPosition: 'bottom',
backBehavior: 'none',
swipeEnabled: false,
lazy: true,
animationEnabled: false,
showIcon: true,
tabBarOptions: {
activeTintColor: 'black',
},
});
The Upload button is need to act as floating action button, when it clicked, it already logging, but not rendering the component.
Any workaround to create the floating action button?
I've some tricks like this https://github.com/react-navigation/react-navigation/pull/1335
But, it is only click and dispatch navigation, not doing floating action button
Regards,
Charlie
you should write this code to your component!
-- you can use ‘react-native-tab-navigator' --
import TabNavigator from 'react-native-tab-navigator';
...
render(){
// console.log('TabRouter this.state:',this.state);
let tabs = [<Home {...this.props}/>,<Chat {...this.props}/>,<Web {...this.props}/>,<User {...this.props}/>];
let a = this.state.loginData.tabList.map((item,key)=>{
// console.log('item:',item);
return(
<TabNavigator.Item
key={key}
selected={this.state.selectedTab === item.type}
title={item.name}
renderIcon={() => <Image source={{uri:item.iconUnselectedUrl}} style={{width:24,height:24,}}/>}
renderSelectedIcon={() => <Image source={{uri:item.iconSelectedUrl}} style={{width:24,height:24}} />}
badgeText={this.state.tabBadge}
onPress={() => this.setState({
selectedTab: item.type,
tabBadge:0,
})}
>
{tabs[key]}
</TabNavigator.Item>
)
});
// console.log('a:',a);
return(
<TabNavigator
hidesTabTouch={true}
sceneStyle={{backgroundColor:'#fff'}}>
{a[0]}
{a[1]}
<TouchableOpacity
key={'add'}
style={{}}
renderIcon={() => <View style={{borderRadius:5,backgroundColor:'#46aee3',
width:width/5,height:49,justifyContent:'center',alignItems:'center'}}>
<Text style={{fontSize:49,padding:0,color:'#ffffff',backgroundColor:'rgba(0,0,0,0)'}}>+</Text></View>}
onPress={()=>this.props.navigation.navigate('SendBlog')}
/>
{a[2]}
{a[3]}
</TabNavigator>
)
}
...
-- update 2018/01/22 --
I think you should
let that;
class UploadMain extends Component {
constructor(props){
super(props);
that = this;
this.state = {
change:false,
};
}
changeState = () => {
this.setState({change:!change});
};
navigationOptions: ({ navigation }) => ({
tabBarLabel: 'Upload',
tabBarIcon: ({ tintColor }) => (
<View>
{that.state.change ? <Text>loading...</Text>:<Icon name="camera" size={26} color={tintColor} />}
</View>
),
tabBarOnPress: () => {
that.changeState;
},
}),
render(){
return (
<View>
....
</View>
)
}
}
If you are using react-navigation version 5.x, you should use tabBarButton to modify.
the code detail you can read
https://medium.com/#my.maithi/react-native-navigation-add-custom-button-in-the-middle-of-tabbar-6c390201a2bb
Hope can help you.

Passing checkbox value to show / hide Password via react native

I'm using Firebase auth I will want to add a Check box, it will display the password in the password text box and hide it when it is clicked again
How to Passing checkbox value to show / hide Password?
This is my Login Page Code:
export default class Login extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: '',
response: ''
}
this.signUp = this.signUp.bind(this)
this.login = this.login.bind(this)
}
async signUp() {
try {
await firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
this.setState({
response: 'Account Created!'
})
setTimeout(() => {
this.props.navigator.push({
id: 'App'
})
}, 500)
} catch (error) {
this.setState({
response: error.toString()
})
}
}
async login() {
try {
await firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
this.setState({
response: 'user login in'
})
setTimeout(() => {
this.props.navigator.push({
id: 'App'
})
})
} catch (error) {
this.setState({
response: error.toString()
})
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.containerInputes}>
<TextInput
placeholderTextColor="gray"
placeholder="Email"
style={styles.inputText}
onChangeText={(email) => this.setState({ email })}
/>
<TextInput
placeholderTextColor="gray"
placeholder="Password"
style={styles.inputText}
password={true}
secureTextEntry={true}
onChangeText={(password) => this.setState({ password })}
/>
</View>
<TouchableHighlight
onPress={this.login}
style={[styles.loginButton, styles.button]}
>
<Text
style={styles.textButton}
>Login</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={this.signUp}
style={[styles.loginButton, styles.button]}
>
<Text
style={styles.textButton}
>Signup</Text>
</TouchableHighlight>
</View>
)
}
}
import React, {useState} from 'react';
import {TextInput} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
const [hidePass, setHidePass] = useState(true);
<TextInput
placeholder="Password"
secureTextEntry={hidePass ? true : false}>
<Icon
name={hidePass ? 'eye-slash' : 'eye'}
onPress={() => setHidePass(!hidePass)} />
<TextInput/>
One way of doing that is to set a state variable like showPassword and toggle it whenever the checkbox is checked. Like so:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
TextInput,
Switch
} from 'react-native';
export default class DemoProject extends Component {
constructor(props) {
super(props);
this.toggleSwitch = this.toggleSwitch.bind(this);
this.state = {
showPassword: true,
}
}
toggleSwitch() {
this.setState({ showPassword: !this.state.showPassword });
}
render() {
return (
<View>
<TextInput
placeholderTextColor="gray"
placeholder="Password"
secureTextEntry={this.state.showPassword}
onChangeText={(password) => this.setState({ password })}
/>
<Switch
onValueChange={this.toggleSwitch}
value={!this.state.showPassword}
/>
<Text>Show</Text>
</View>
)
}
}
AppRegistry.registerComponent('DemoProject', () => DemoProject);
NOTE: This won't work if you set the password prop!!!
So just use a regular TextInput and utilize the secureTextEntry prop.
here is my way of doing it
const LoginScreen = props => {
const [icon, setIcon] = useState("eye-off")
const [hidePassword, setHidePassword] = useState(true)
_changeIcon = () => {
icon !== "eye-off"
? (setIcon("eye-off"), setHidePassword(false))
: (setIcon("eye"), setHidePassword(true))
}
i used native base for textInput
<Input
secureTextEntry={hidePassword}
placeholder="Password"
placeholderTextColor={palette.gray}
/>
<Icon name={icon} size={20} onPress={() => _changeIcon()} />
this will change the secureTextEntry on click
Please correct me if I am wrong, are you asking how to create a check box? If so, you have two routes, either use a 3rd party library from one of the many check boxes on the web or you can create one yourself.
Steps:
download a icon library as such https://github.com/oblador/react-native-vector-icons so you can use the two material design icons from enter link description here eg. checkbox-blank-outline and checkbox-marked to emulate clicked and not clicked
using those two new icons, simply create a new component with what ever functionality you desire and handle all states and such the way you want.
Basic implementation:
Have a state that controls if it was checked or not
Have a onPress function to handle both states and trigger the respective props
// the on press function
onPress = () => {
if (this.sate.checked) {
this.props.checked();
} else {
this.props.unChecked();
}
}
// the rendered component
<Icon name={this.state.checked ? "checkbox-marked" : "checkbox-blank-outline" onPress={this.onPress}/>
this is how i did in simple way,
my checkbox and password component,
<input style={ inputUname } type={this.state.type} placeholder="Password" value={ this.state.password } onChange={this.handlePassword}/>
<Checkbox defaultChecked={false} onSelection={this.showPassword} value="false" name="Checkbox" label="Show password"/>
my state,
this.state = {
type: 'input'
}
here is my show password event,
showPassword(e){
this.setState( { showpassword: !this.state.showpassword }) // this is to change checkbox state
this.setState( { type: this.state.type === 'password' ? 'text' : 'password' }) // this is to change input box type text/password change
}
enter image description here
const [password, setPassword] = useState("")
const [passwordVisible, setPasswordVisible] = useState(true)
<TextInput
mode='outlined'
style={{ flex: 1, marginHorizontal: 20, marginTop: 30 }}
autoCapitalize="none"
returnKeyType="next"
label=' Password '
keyboardType="default"
underlineColorAndroid={'rgba(0,0,0,0)'}
right={<TextInput.Icon color={colors.white} name={passwordVisible ? "eye" : "eye-off"} onPress={onPressEyeButton} />}
text='white'
maxLength={50}
onChangeText={(text) => { setPassword(text) }}
value={password}
defaultValue={password}
theme={styles.textInputOutlineStyle}
secureTextEntry={passwordVisible}
/>
textInputOutlineStyle: {
colors: {
placeholder: colors.white,
text: colors.white,
primary: colors.white,
underlineColor: 'transparent',
background: '#0f1a2b'
}
},
[1]: https://i.stack.imgur.com/C7ist.png
Step1: Create a useState hook to store the initial values of password and secureTextEntry:
const [data, setData] = useState({
password: '',
isSecureTextEntry: true,
});
Step2: Update the state according to the conditions:
<View>
<TextInput
style={styles.textInput}
placeholder="Enter Password"
secureTextEntry={data.isSecureTextEntry ? true : false}
onChangeText={data => {
setData({
password: data,
//OR
/*
//Array destructuring operator to get the existing state i.e
...data
*/
//and then assign the changes
isSecureTextEntry: !data.isSecureTextEntry,
});
}}></TextInput>
<TouchableOpacity
onPress={() => {
setData({
//...data,
isSecureTextEntry: !data.isSecureTextEntry,
});
}}>
<FontAwesome
name={data.isSecureTextEntry ? 'eye-slash' : 'eye'}
color="gray"
size={25}
paddingHorizontal="12%"
/>
</TouchableOpacity>
</View>
<View>
<Input
style={styles.input}
onChangeText={onChangeData}
multiline={false}
secureTextEntry={!showPassword}
textContentType={"password"}
value={data.password}
placeholder="Password"
/>
<TouchableHighlight
style={{
textAlign: "right",
position: "absolute",
right: 20,
bottom: 22,
zIndex: 99999999,
}}
onPress={() => setShowPassword(!showPassword)}
>
<>
{showPassword && (
<Ionicons name="eye-outline" size={22} color="#898A8D" />
)}
{!showPassword && (
<Ionicons name="eye-off-outline" size={22} color="#898A8D" />
)}
</>
</TouchableHighlight>
</View>;

Categories

Resources