React native code is unable to send data to django api - javascript

I am a beginner and I'm using Django in the backend of my react native app. I am unable to add data to the django admin panel from my app using fetch method. I am not getting any errors but my data is not getting posted to the backend.I have used the django api as the url in fetch method.
Please let me know if any other code snippet is required to check.
Would appreciate some help here.
export class LoginScreen extends Component {
constructor() {
super();
this.state = {
email: '',
name: '',
};
}
updateValue(text, field) {
if (field == 'email') {
this.setState({
email: text,
});
} else if (field == 'pwd') {
this.setState({
pwd: text,
});
}
}
submit() {
let collection = {};
collection.email = this.state.email;
collection.pwd = this.state.pwd;
console.warn(collection);
let url='http://10.0.0.2:8000/api/mdlApp/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(collection),
})
.then((response) => response.json())
.then((collection) => {
console.log('Success:', collection);
})
.catch((error) => {
console.error('Error:', error);
});
}
render() {
return (
<ImageBackground source={require('../images/bg4.png')} style={styles.bg}>
<SafeAreaView style={styles.container}>
<Logo />
<View style={styles.container1}>
<TextInput
style={styles.inputBox}
name="email"
placeholder="Enter Your Email"
placeholderTextColor="#ffffff"
onChangeText={(text) => this.updateValue(text, 'email')}
/>
<TextInput
style={styles.inputBox}
name="pwd"
placeholder="Enter Your Password"
secureTextEntry={true}
placeholderTextColor="#ffffff"
onChangeText={(text) => this.updateValue(text, 'pwd')}
/>
<TouchableOpacity
//onPress={() => this.props.navigation.navigate('HomeApp')}
onPress={() => this.submit()}
style={styles.button}
htmlType="submit">
<Text style={styles.buttonText}> LOGIN </Text>
</TouchableOpacity>
</View>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Don't have an account yet?</Text>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Register')}
style={styles.signupButton}>
<Text>Register Now</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
</ImageBackground>
);
}
}

change ur code as follows..install axios first
submit = () => {
const url='http://10.0.0.2:8000/api/mdlApp/'
let collection = {
email: this.state.email,
pwd: this.state.pwd
};
axios.post(`${url}`, collection, {
headers: {
'content-type': 'application/json'
}
} ).then(res => {
console.log(res.data)
}))
}

Related

Unable to Type in <Formik> Field

interface FormValues {
friendEmail: string;
}
const initialValues: FormValues = {
friendEmail: '',
};
export const Page: React.FunctionComponent<PageProps> = ({
toggleShowPage,
showPage,
}) => {
const [errorMessage, setErrorMessage] = useState('');
const validationSchema = emailValidationSchema;
useEffect(() => {
if (showPage) return;
initialValues.friendEmail = '';
}, [showPage]);
const [
createUserRelationMutation,
{
data: addingFriendData,
loading: addingFriendLoading,
error: addingFriendError,
called: isMutationCalled,
},
] = useCreateUserRelationMutation({
onCompleted: (data: any) => {
showAlert();
},
});
const addFriend = React.useCallback(
(id: Number) => {
console.log('Whats the Id', id);
createUserRelationMutation({
variables: {
input: { relatedUserId: id, type: RelationType.Friend, userId: 7 },
},
});
},
[createUserRelationMutation],
);
const getFriendId = React.useCallback(
(data: any) => {
//console.log('Email', initialValues.friendEmail);
if (data) {
if (data.users.nodes.length == 0) {
console.log('No user');
setErrorMessage('User Not Found');
Alert.alert('User Not Found');
} else {
console.log('ID', data.users.nodes[0].id);
addFriend(Number(data.users.nodes[0].id));
}
}
},
[addFriend],
//[friendEmail, addFriend],
);
const [loadUsers] = useUsersLazyQuery({
onCompleted: getFriendId,
onError: _onLoadUserError,
});
const handleSubmitForm = React.useCallback(
(values: FormValues, helpers: FormikHelpers<FormValues>) => {
console.log('Submitted');
loadUsers({
variables: {
where: { email: values.friendEmail },
},
});
//setFriendEmail('');
values.friendEmail = '';
},
[loadUsers],
//[loadUsers, friendEmail]
);
if (!addingFriendLoading && isMutationCalled) {
if (addingFriendData) {
console.log('Checking');
}
if (addingFriendError) {
console.log('errorFriend', addingFriendError.message);
}
}
return (
<Modal
visible={showAddFriendEmailPage}
animationType="slide"
transparent={true}>
<SafeAreaView>
<View style={scaledAddFriendEmailStyles.container}>
<View style={scaledAddFriendEmailStyles.searchTopContainer}>
<View style={scaledAddFriendEmailStyles.searchTopTextContainer}>
<Text
style={scaledAddFriendEmailStyles.searchCancelDoneText}
onPress={toggleShowPage}>
Cancel
</Text>
<Text style={scaledAddFriendEmailStyles.searchTopMiddleText}>
Add Friend by Email
</Text>
<Text style={scaledAddFriendEmailStyles.searchCancelDoneText}>
Done
</Text>
</View>
<View style={scaledAddFriendEmailStyles.searchFieldContainer}>
<Formik
initialValues={initialValues}
onSubmit={handleSubmitForm}
validationSchema={validationSchema}>
{({
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
values,
}) => (
<View>
<View>
<Item style={scaledAddFriendEmailStyles.searchField}>
<TextInput
style={scaledAddFriendEmailStyles.searchText}
placeholder="Email"
onChangeText={handleChange('friendEmail')}
//onChangeText={e => console.log('Workinggg')}
onBlur={handleBlur('friendEmail')}
value={values.friendEmail}
autoCapitalize="none"
/>
{/* <Field
component={Input}
name='friendEmail'
placeholder="Email"
//handleChange={handleChange}
handleBlur={handleBlur}
//onChange={handleChange}
//onChangeText={handleChange('friendEmail')}
//onBlur={handleBlur('friendEmail')}
value={values.friendEmail}
autoCapitalize="none"
/> */}
</Item>
</View>
<View>
<Button
onPress={handleSubmit}>
<Text>
Add Friend{' '}
</Text>
</Button>
</View>
</View>
)}
</Formik>
</View>
</View>
</View>
</SafeAreaView>
</Modal>
);
};
Why am I unable to write anything inside my Input field? I have tried using onChangeand handleChangeboth but it doesn't make a difference. Other SO answers suggested that I should remove value but examples of Formik usage that I see online suggest otherwise.
I am trying to follow this for my Formik validation:
https://heartbeat.fritz.ai/build-and-validate-forms-in-react-native-using-formik-and-yup-6489e2dff6a2
EDIT:
I also tried with setFieldValuebut I still cannot type anything.
const initialValues: FormValues = {
friendEmail: '',
};
export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({
toggleShowPage,
showAddFriendEmailPage,
}) => {
const [errorMessage, setErrorMessage] = useState('');
const validationSchema = emailValidationSchema;
useEffect(() => {
if (showAddFriendEmailPage) return;
initialValues.friendEmail = '';
}, [showAddFriendEmailPage]);
const _onLoadUserError = React.useCallback((error: ApolloError) => {
setErrorMessage(error.message);
Alert.alert('Unable to Add Friend');
}, []);
const [
createUserRelationMutation,
{
data: addingFriendData,
loading: addingFriendLoading,
error: addingFriendError,
called: isMutationCalled,
},
] = useCreateUserRelationMutation({
onCompleted: (data: any) => {
showAlert();
},
});
const addFriend = React.useCallback(
(id: Number) => {
console.log('Whats the Id', id);
createUserRelationMutation({
variables: {
input: { relatedUserId: id, type: RelationType.Friend, userId: 7 },
},
});
},
[createUserRelationMutation],
);
const getFriendId = React.useCallback(
(data: any) => {
//console.log('Email', initialValues.friendEmail);
if (data) {
if (data.users.nodes.length == 0) {
console.log('No user');
} else {
console.log('ID', data.users.nodes[0].id);
addFriend(Number(data.users.nodes[0].id));
}
}
},
[addFriend],
//[friendEmail, addFriend],
);
const [loadUsers] = useUsersLazyQuery({
onCompleted: getFriendId,
onError: _onLoadUserError,
});
const handleSubmitForm = React.useCallback(
(values: FormValues, helpers: FormikHelpers<FormValues>) => {
console.log('Submitted');
loadUsers({
variables: {
where: { email: values.friendEmail },
},
});
//setFriendEmail('');
values.friendEmail = '';
},
[loadUsers],
//[loadUsers, friendEmail]
);
return (
<Modal
visible={showPage}
animationType="slide"
transparent={true}>
<SafeAreaView>
<View style={scaledAddFriendEmailStyles.container}>
<View style={scaledAddFriendEmailStyles.searchFieldContainer}>
<Formik
initialValues={initialValues}
onSubmit={handleSubmitForm}
validationSchema={validationSchema}>
{({
handleChange,
setFieldValue,
handleBlur,
handleSubmit,
isSubmitting,
values,
}) => {
const setEmail = (friendEmail: string) => {
setFieldValue('friendEmail', friendEmail)
}
return(
<View>
<View>
<Item>
<TextInput
placeholder="Email"
onChangeText={setEmail}
onBlur={handleBlur('friendEmail')}
value={values.friendEmail}
autoCapitalize="none"
/>
</Item>
</View>
<View >
<Button
onPress={handleSubmit}>
<Text >
Add Friend{' '}
</Text>
</Button>
</View>
</View>
)}}
</Formik>
</View>
</View>
</View>
</SafeAreaView>
</Modal>
);
};
Formik's Field component doesn't support React native yet. Check this github issue for more details
However you can make use of TextInput in place of field and use it with onChangeText handler
<Formik
initialValues={initialValues}
onSubmit={handleSubmitForm}
validationSchema={validationSchema}>
{({
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
values,
}) => (
<View>
<View>
<Item style={scaledAddFriendEmailStyles.searchField}>
<TextInput
placeholder="Email"
onChangeText={handleChange('friendEmail')}
onBlur={handleBlur('friendEmail')}
value={values.friendEmail}
/>
</Item>
</View>
<View >
<Button
onPress={handleSubmit}
>
<Text >
Add Friend{' '}
</Text>
</Button>
</View>
</View>
)}
</Formik>
you can read more about Formik's usage with react-native in its documentation here
try this:
<Input
placeholder="Email"
onChange={e => setFieldValue('friendEmail', e.currentTarget.value)}
onBlur={handleBlur}
value={values.friendEmail}
autoCapitalize="none"
/>
I think there are a couple of issues in your codebase.
onChangeText={handleChange('friendEmail')}. It will trigger the handleChange while rendering the component not when you are actualy typing in the input box.
handleChange function of Formik takes React.ChangeEvent instead of value. Check here . While onChangeText of react-native provides changed text of the input not event. Check here
You can use setFieldValue function for this case:
<Formik
initialValues={initialValues}
onSubmit={handleSubmitForm}
validationSchema={validationSchema}>
{({
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
values,
setFieldValue
}) => {
const setEmail = (email) => {
setFieldValue('friendEmail', email)
}
return (
<View>
<View>
<Item style={scaledAddFriendEmailStyles.searchField}>
<TextInput
placeholder="Email"
onChangeText={setEmail}
value={values.friendEmail}
/>
</Item>
</View>
</View>
)
}}
</Formik>
Please Note: I've never used formik with react-native. Just trying to connect the dots.
Formik now works fine with React Native, but another thing to be aware of is that the name in your form control must match the name of the property in the schema used by Formik.
For example, if using the following Yup schema:
const schema = yup.object({
personName: yup.string().required('Name required')
});
Then the following won't work because the Yup schema (personName) and the form control (nameofPerson) don't match; the user won't be able to type into the field:
<Form.Control
name="nameOfPerson"
value={values.personName}
onChange={handleChange}
onBlur={handleBlur}
type="text"
isValid={!errors.personName && !!touched.personName}
isInvalid={!!errors.personName && !!touched.personName}
/>
To make it work, the name should be the same as the Yup property; in this case, personName:
<Form.Control
name="personName"
value={values.personName}
onChange={handleChange}
onBlur={handleBlur}
type="text"
isValid={!errors.personName && !!touched.personName}
isInvalid={!!errors.personName && !!touched.personName}
/>
This example is using React-Bootstrap Form.Control but should apply to any manner of creating form controls.

React native authentication using laravel backend API

I'm new to react-native. I currently try to set the login of react-native by using the Laravel API. The API that I used already tested and its work. But when I tried to put in the react-native, it shows the error while i called the API.
The warning in the emulator is:
Possible Unhandled Promise Rejection (id:0):
TypeError: Network request failed
Here is my code.
import React, { Component } from 'react';
import {
StyleSheet,
View,
TextInput,
Text,
TouchableOpacity,
Alert,
AsyncStorage,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import Logo from '../components/Logo';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
}
};
signup(){
Actions.signup()
}
home(){
Actions.home()
}
handleLogin = () => {
fetch('http://localhost:8888/api/login',{
method: 'POST',
header:{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
})
})
.then((response) => response.json())
.then((res) => {
if (res.success === true){
alert(res.message)
}else{
alert(res.message)
}
alert('test')
})
}
render() {
return (
<View style={styles.container}>
<Logo/>
<View style={styles.inputContainer}>
<TextInput style={styles.inputBox}
underlineColorAndroid='0,0,0,0'
placeholder='Email'
placeholderTextColor= 'grey'
keyboardType= 'email-address'
onChangeText={(text) => this.setState({email:text})}
onSubmitEditing={()=> this.password.focus()}
/>
<TextInput style={styles.inputBox}
underlineColorAndroid='0,0,0,0'
placeholder='Password'
placeholderTextColor= 'grey'
secureTextEntry= {true}
ref={(input) => this.password = input}
onChangeText={(text) => this.setState({password:text})}
/>
<TouchableOpacity style={styles.button} onPress={this.handleLogin}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
</View>
<View style={styles.signupText}>
<Text>Don't have an account? </Text>
<TouchableOpacity onPress={this.signup}>
<Text style={styles.signupButton}>Signup</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Anyone know what's the problem?
Problem solved by setup the adb and use the adb reverse command.
EXAMPLE
adb reverse tcp:8081 tcp:3333
https://stackoverflow.com/a/39108921/12988525

react native - undefined is not an object(evaluating 'password.toString')

So, basically, I have two JavaScript files, in one of them there's a function that authenticates to an API and the other one is the login screen running in the emulator. When I try to authenticate, I get the error:
undefined is not an object (evaluating 'password.toString')
This is the login screen file:
import React, {Component} from 'react';
import {View, Text, TextInput, TouchableOpacity} from 'react-native';
import styles from './login-styles';
import {auth} from '../../fetches/auth';
class LoginBox extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: ''
}
}
render = () => {
return(
<View style={styles.box}>
<View style={styles.header}>
<Text style={{fontSize: 28}}>Bem-vindo ao PostBag v 0.0.2</Text>
</View>
<View styles={styles.app}>
<TextInput style={styles.square}
keyboardType="numeric"
placeholder='Insira sua matrúcla'
onChangeText={(text) => this.setState({username: text})}
value={this.state.username}
/>
<TextInput style={styles.square}
secureTextEntry
placeholder='Insira sua senha'
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
/>
<TouchableOpacity
style={styles.button}
onPress={() => auth((this.state.username, this.state.password))}
>
<Text style={styles.buttonTxt}>POST</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
export default LoginBox;
This is the authentication function:
import {Alert} from 'react-native';
export function auth(username, password) {
fetch('https://suap.ifrn.edu.br:443/api/v2/autenticacao/token/',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-csrftoken': 'NDML6yy6HgTUIoypfWMZHMKZ32lgJf5PsNolVnLgewanw5YM4rqwkuvgkyAhEYEA'
},
body: JSON.stringify({
username: username.toString(),
password: password.toString()
})
}).then(function(response) {
var json = response.json()
json.then((data) => {
token = data.token
if (typeof token === 'undefined') {
Alert.alert('Não foi possível fazer login')
}
else {
Alert.alert('Login feito com sucesso')
}
})
})
}
I would really appreciate if anyone could help me with that. Everything that I tried did not work.
I think, because of that password or username is null or undefined at that moment. You can check if they are defined and they are strings as below,
body: JSON.stringify({
username: typeof username === 'string' ? username.toString() : '',
password: typeof password === 'string' ? password.toString() : ''
})
and your view should be changed as follow,
onPress={() => auth(this.state.username, this.state.password)}
Delete extra brackets from onPress.
auth(this.state.username, this.state.password)
Change this
<TouchableOpacity
style={styles.button}
onPress={() => auth((this.state.username, this.state.password))}
>
to
<TouchableOpacity
style={styles.button}
onPress={() => auth(this.state.username, this.state.password)}
>
Also, whenever you're accessing objects with dot operator (.toString()), it's safe to check if the object is present in the first place.
So it's a good idea to convert this
body: JSON.stringify({
username: username.toString(),
password: password.toString()
})
to
body: JSON.stringify({
username: username && username.toString(),
password: password && password.toString()
})

Firebase unsupported browser

I'm using firebase for my react-native application. I don't know what happen when i trying to sign in using firebase authentication this error show. But, Yesterday it's not happen in my application. I don't know why it happened. Please help me i'm stuck right now.
Error image is on link below
this is my source code:
import React, { Component } from 'react';
import {
Text,
View,
TouchableOpacity,
TextInput,
Image,
Button,
AsyncStorage
} from 'react-native';
import FBSDK, { LoginButton, AccessToken } from 'react-native-fbsdk';
import { GoogleSignin, GoogleSigninButton } from 'react-native-google-signin';
import styles from '../components/style.js';
import firebase from '../components/Firebase.js';
export default class Signin extends Component {
constructor(){
super();
this.state={
email:'',
password: ''
}
}
componentWillMount() {
GoogleSignin.hasPlayServices({ autoResolve: true }).then(() => {
GoogleSignin.configure ({
webClientId: '678031332619-ol6s25inanfpk0fkudjt5dhdhfd1m9ov.apps.googleusercontent.com'
})
})
.catch((err) => {
console.log("Play services error", err.code, err.message);
})
}
signIn(){
firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((userData) => {
AsyncStorage.setItem('userData', JSON.stringify(userData))
alert("Sign in Success")
this.props.navigation.navigate('Form');
}).catch((e) => {
alert(e)
})
}
handleSigninGoogle() {
GoogleSignin.signIn().then((user) => {
console.log(user);
}).catch((error) => {
console.log('WRONG SIGNIN', error);
}).done();
}
Signout() {
GoogleSignin.signOut()
.then(() => {
console.log('out');
})
.catch((err) => {
});
}
render() {
console.ignoredYellowBox = ['Remote debugger'];
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Text style={styles.title}> 41 Studio IT Solutions </Text>
<TextInput
style={styles.loginInput}
onChangeText={(email) => this.setState({email})}
value={this.state.email}
underlineColorAndroid='transparent'
placeholder='Email'
/>
<TextInput
style={styles.loginInput}
onChangeText={(password) => this.setState({password})}
value={this.state.password}
underlineColorAndroid='transparent'
placeholder='Password'
secureTextEntry
/>
<View style={styles.main}>
<TouchableOpacity
style={styles.button}
onPress={this.signIn.bind(this)}
>
<Text style={styles.buttonText}> Sign In </Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => navigate('Register')}
>
<Text style={styles.buttonText}> Register </Text>
</TouchableOpacity>
</View>
<LoginButton
style={styles.facebookButton}
publishPremissions={["publish_actions"]}
onLoginFinished= {(error, result) => {
if(error) {
alert(error);
}
else if (result.isCancelled){
console.log('Cancelled')
}
else {
AccessToken.getCurrentAccessToken().then((data) => {
console.log(data.accessToken.toString())
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken.toString());
firebase.auth().signInWithCredential(credential).catch((e) => console.log(e))
})
}
}
}
onLogoutFinished={() => console.log("logout")}
/>
<GoogleSigninButton
style={styles.googleButton}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Light}
onPress={this.handleSigninGoogle.bind(this)}/>
<Button onPress={() => this.Signout.bind(this)} title="Signout" />
</View>
);
}
}
UPDATE: firebase#4.5.2 resolved this issue
This is the related issue, assuming you are using firebase#4.5.1
https://github.com/firebase/firebase-js-sdk/issues/223
Until a newer version is release, quick fix is to downgrade to 4.5.0

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