inputs in component aren't updating correctly - javascript

I have component that is going to be used many times. It's basically to inputs that will represent two width and height dimensions.
Couple of things going on with them right now. When I start typing in them, when they are both empty, the last character is not recorded. if I type:
1234 x 1234
when I refresh the inputs show:
1234 x 123
then if I edit one of the inputs, the other will just go blank.
Here's my code:
import React from 'react';
// Shared Components
import { FlexRow } from 'components/shared/Flexbox';
import { TextInput } from 'components/shared/TextInput';
export class RenderDimensionsInput extends React.Component {
state = {
readOnly: '',
width: null,
height: null
};
handleChange = e => {
console.log('e.target.name', e.target.name);
this.setState({ [e.target.name]: e.target.value });
console.log('this.state.height', this.state.height);
console.log('this.state.width', this.state.width);
this.props.onChange(this.state.height, this.state.width);
};
render() {
return (
<div>
<FlexRow>
<TextInput
label={this.props.label}
style={{ width: '135px', marginRight: '10px' }}
defaultValue={this.props.values.width}
name="width"
// onChange={this.props.onChange}
onChange={e => this.handleChange(e)}
/>
<span>x</span>
<TextInput
style={{ width: '135px', marginLeft: '10px' }}
defaultValue={this.props.values.height}
name="height"
// onChange={this.props.onChange}
onChange={e => this.handleChange(e)}
/>
</FlexRow>
</div>
);
}
}
export class TextInput extends React.Component {
state = {
readOnly: '',
};
render() {
return (
<FlexColumn
style={{
alignItems: 'baseline',
paddingBottom: s[3],
}}>
<Input
{...this.props}
type={this.props.type || 'text'}
defaultValue={this.props.defaultValue}
onChange={this.props.onChange}
readOnly={this.state.readOnly}
/>
<Label>{this.props.label}</Label>
</FlexColumn>
);
}
}

You are using the value from state directly after setting the state, but setState is async which means that there is no guarantee that at that moment you are using the latest state in: this.props.onChange(this.state.height, this.state.width);
So it is better to use it that way:
this.setState({ [e.target.name]: e.target.value }, () => {
this.props.onChange(this.state.height, this.state.width);
});

Related

How do I set autofocus to an input that's inside a select dropdown?

I have an input field inside a select dropdown. I need to focus on that input box as soon as the dropdown is shown when the user clicks on it. I tried using refs, but that doesn't seem to work. I'm using antd 3.26.14 and React 16.8.6. Here is the code:
<Select
labelInValue
open={isOpenSelectCategory}
onDropdownVisibleChange={onDropdownVisibleChange}
placeholder="Select Category"
onChange={() => {
searchDropdownOptions('formCategories', '');
setCategoryInputValue('');
}}
notFoundContent={null}
dropdownRender={menu => (
<>
<div
onMouseDown={lockSelectCategoryClose}
onMouseUp={lockSelectCategoryClose}
style={{ marginBottom: '10px' }}
>
<Input
value={categoryInputValue}
ref={inputRef}
onChange={event => {
searchDropdownOptions(
'formCategories',
event.target.value,
);
setCategoryInputValue(event.target.value);
}}
placeholder="Search category or create new one"
/>
...
The useEffect for the Input ref:
useEffect(() => {
if (inputRef.current) inputRef.current.focus();
}, [inputRef]);
I've tried variations of the above useEffect, where instead of listening to changes on inputRef, I've listened to the change when the dropdown gets loaded. Neither of them worked though.
Any help here will be much appreciated...
Try to use ref={(input) => input && input.focus()} in combination with autofocus property e.g.:
<Input
autofocus
ref={(input) => input && input.focus()}
...
/>
Here is a working stackblitz for a react class component.
NOTE: The issue with this solution is that it focuses input on any re-render (which might not be desired).
See also how-to-set-focus-on-an-input-field-after-rendering for more options.
Code for the linked complete example:
import React, { useFocus } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Select, Divider, Input } from 'antd';
import { PlusOutlined } from '#ant-design/icons';
const { Option } = Select;
let index = 0;
class App extends React.Component {
state = {
items: ['jack', 'lucy'],
name: '',
};
onNameChange = (event) => {
this.setState({
name: event.target.value,
});
};
addItem = () => {
console.log('addItem');
const { items, name } = this.state;
this.setState({
items: [...items, name || `New item ${index++}`],
name: '',
});
};
render() {
// const [inputRef, setInputFocus] = useFocus();
const { items, name } = this.state;
return (
<Select
style={{ width: 240 }}
placeholder="custom dropdown render"
dropdownRender={(menu) => (
<div>
{menu}
<Divider style={{ margin: '4px 0' }} />
<div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}>
<Input
autofocus
ref={(input) => input && input.focus()}
style={{ flex: 'auto' }}
value={name}
onChange={this.onNameChange}
/>
<a
style={{
flex: 'none',
padding: '8px',
display: 'block',
cursor: 'pointer',
}}
onClick={this.addItem}
>
<PlusOutlined /> Add item
</a>
</div>
</div>
)}
>
{items.map((item) => (
<Option key={item}>{item}</Option>
))}
</Select>
);
}
}
ReactDOM.render(<App />, document.getElementById('container'));

Pass function to semantic ui clearable prop

I have small portion of my app rendering a dropdown selection so users can view some brief information about library versions within the app.
The first dropdown is for the user to pick what they want view, for brevity I just added the relevant option for this question.
The second dropdown renders a fetched list of numbers pertaining to deviceIds. These deviceIds are fetched from a child class and then passed via props up to the parent class.
Now, In Semantic-UI-React, they have a dropdown module with a clearable prop which I am using on this dropdown populated with deviceIds. Below in VersionNumber class, you can see the props defined for the aforementioned dropdown.
The clearable prop lets the user remove the selected input from the dropdown. However, in my app when the input is removed it calls the onChange function which I do not want. I tried passing a custom change function to the clearable prop where I'm attempting to reset the state variable deviceId back to a undefined value if it's "cleared" by the user.
Is this possible? I'm pretty sure I'm taking the correct approach, but may be having an issue where the onChange function is firing before the clearable passed function.
I have a codesandbox that reproduces this problem here.
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import {
Dropdown,
Form,
Divider,
Input,
Message,
Loader
} from "semantic-ui-react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
viewSelection: "",
deviceId: "",
versionNum: "",
isLoading: true
};
}
handleViewSelection = (e, { value }) => {
this.setState({ viewSelection: value }, () => {
console.log("view election --> ", this.state.viewSelection);
});
};
onDeviceIdChange = async (e, { value }) => {
console.log("device id value -->", value);
this.setState({ deviceId: value }, () => {
console.log(
"deviceId value updated to state on select -->",
this.state.deviceId
);
});
try {
const { data } = await axios.get(`/deviceId/${value}`);
const version = data.data.versionNumber;
this.setState({ versionNum: version.version, isLoading: false }, () => {
console.log("callback from admin version fetch", this.state.versionNum);
});
} catch (error) {
console.error(Error(`Error getting the selected deviceId ${error.message}`));
}
};
handleClear = () => {
this.setState({ deviceId: "" }, () => {
console.log("handleClear function fired");
});
};
render() {
const { viewSelection, deviceId, versionNum, isLoading } = this.state;
return (
<div
style={{ display: "flex", minHeight: "100vh", flexDirection: "column" }}
>
<div style={{ flex: 1 }}>
<div
style={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
flex: "1"
}}
>
<div style={{ width: "1000px" }}>
<Divider style={{ marginTop: "7em" }} horizontal>
View Data
</Divider>
<Message style={{ marginTop: "2em" }} info>
<Message.Header>
Want to see more specific information? Log in
here.
</Message.Header>
</Message>
<Form.Field style={{ marginTop: "2em" }}>
<label>Select data to view</label>
<Dropdown
scrolling
placeholder="Pick an option"
value={viewSelection}
fluid
selection
multiple={false}
search
options={viewOptions}
onChange={this.handleViewSelection}
/>
</Form.Field>
{this.state.viewSelection && (
<div style={{ marginTop: "2em" }}>
{viewSelection && viewSelection === "versionNumber" ? (
<>
<VersionNumber
onDeviceIdChange={this.onDeviceIdChange}
deviceId={deviceId}
handleClear={this.handleClear}
/>
<div>
<label style={{ display: "block", marginTop: "2em" }}>
Version Number
</label>
{isLoading ? (
<Loader active inline="centered" />
) : (
<Input value={versionNum} fluid readOnly />
)}
</div>
</>
) : null}
</div>
)}
</div>
</div>
</div>
</div>
);
}
}
class VersionNumber extends Component {
constructor(props) {
super(props);
this.state = {
deviceId: "",
deviceIds: []
};
}
async componentDidMount() {
await this.getDeviceIds();
}
getDeviceIds = async () => {
try {
const { data } = await axios.get("/deviceIds");
console.log("device IDs --> ", data);
const deviceIds = data.data.deviceIds;
this.setState(
{
deviceIds: deviceIds
},
() => {
console.log(
"setState callback with updatesd deviceIds state -->",
this.state.deviceIds
);
}
);
} catch (error) {
console.error(Error(`Error getting deviceIds: ${error.message}`));
}
};
render() {
const { onDeviceIdChange, deviceId, handleClear } = this.props;
const { deviceIds } = this.state;
return (
<Form.Field required>
<label style={{ display: "block" }}>Device Id</label>
<Dropdown
id="deviceId"
value={deviceId}
onChange={onDeviceIdChange}
selection
fluid
placeholder="Please select an device id"
clearable={handleClear}
options={deviceIds.map(id => {
return {
text: id.id,
value: id.id,
key: id.id
};
})}
style={{ marginTop: ".33", marginBottom: "2em" }}
/>
</Form.Field>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
clearable prop expects a boolean value. You can change your onChange callback to consider the scenario where the value is going to be passed in as null / undefined
The function can be modified as below to reset the deviceId and prevent the API call
onDeviceIdChange = async (e, { value }) => {
// VALUE WILL BE PASSED IN AS "" WHEN THE CLEAR OPTION IS CLICKED
console.log("device id value -->", value);
this.setState({ deviceId: value }, () => {
console.log(
"deviceId value updated to state on select -->",
this.state.deviceId
);
});
// THIS IS THE CONDITION TO CATCH THE CLEARABLE INVOCATION
if(!value) {
this.handleClear();
return;
}
...
};
if(!value) return; Think of this condition as the execution that the clearable option will invoke. You can invoke anything before the return to ensure that your application handles the clear option in the way you expect it to.

How to pass state from child component to parent in React.JS?

I have a form that has 10+ input fields that update the state of the class. To make things look cleaner I moved all input fields with labels into a separate component so I could re-use it for each input instead. This component takes 2 parameters and serves as a child in my main class.
child component:
const Input = ({ name, placeholder }) => {
return (
<div className="wrapper">
<Row className="at_centre">
<Col sm="2" style={{ marginTop: "0.5%" }}><Form.Label>{ name }</Form.Label></Col>
<Col sm="5"><Form.Control placeholder={ placeholder }/></Col>
</Row>
</div>
)
}
parent:
state = { name: '', description: '' }
handleSubmit = (e) => {
e.preventDefault()
console.log(this.state);
}
render(){
return(
<Form style={{ marginBottom: "5%", padding: 10 }} onSubmit={ this.handleSubmit } >
<Input name="Name: " placeholder="How is it called?" onChange={ (event) => this.setState({name: event.target.value}) }/>
<Input name="Description: " placeholder="Please describe how does it look like?" onChange={ (event) => this.setState({description: event.target.value}) }/>
<Button variant="outline-success" size="lg" type="submit" >SUBMIT</Button>
</Form>
)
}
After I did that I can't find the way how to update the state from my child components when the text is changed. All my attempts to do so either crashed the website or did nothing. I am still new to React.js so any feedback is appreciated.
Pass onChange event to your child component and wire it with Form.Control control.
Your Input component will be,
const Input = ({ name, placeholder, onChange }) => {
return (
<div className="wrapper">
<Row className="at_centre">
<Col sm="2" style={{ marginTop: "0.5%" }}>
<Form.Label>{name}</Form.Label>
</Col>
<Col sm="5">
<Form.Control onChange={onChange} placeholder={placeholder} />
</Col>
</Row>
</div>
);
};
And your Parent component is,
class Parent extends React.Component {
state = { name: "", description: "" };
handleSubmit = e => {
e.preventDefault();
console.log(this.state);
};
render() {
return (
<Form
style={{ marginBottom: "5%", padding: 10 }}
onSubmit={this.handleSubmit}
>
<Input
name="Name: "
placeholder="How is it called?"
onChange={event => this.setState({ name: event.target.value })}
/>
<Input
name="Description: "
placeholder="Please describe how does it look like?"
onChange={event => this.setState({ description: event.target.value })}
/>
<Button variant="outline-success" size="lg" type="submit">
SUBMIT
</Button>
</Form>
);
}
}
Working Codesandbox here.
In React, properties flow from the parent component to the child component, so you cannot directly "pass" the state from the child to the parent.
What you can do however is to have the parent pass a callback function to the child that will be called to update the parent's state.
Here is an example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
};
}
updateName(name) {
if (name === this.state.name) return;
this.setState({ name });
}
render() {
return (
<div>
<p>The name is {this.state.name}</p>
<ChildComponent handleNameUpdate={name => this.updateName(name)} />
</div>
);
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
};
}
handleInputChange(e) {
this.setState({ name: e.target.value });
this.props.handleNameUpdate(e.target.value)
}
render() {
return <input type="text" value={this.state.name} onChange={e => this.handleInputChange(e)} />;
}
}
You have to build what is known as a controlled component.
const Input = ({ label, name, onChange, placeholder }) => (
<div className="wrapper">
<Row className="at_centre">
<Col sm="2" style={{ marginTop: "0.5%" }}>
<Form.Label>{ label }</Form.Label></Col>
<Col sm="5">
<Form.Control name={ name }
value={ value }
placeholder={ placeholder }
onChange={ onChange }
/>
</Col>
</Row>
</div>
)
And in your parent,
state = { name: '', description: '' }
handleChange = ({ target: { name, value } }) => this.setState({ [name]: value })
render() {
const { name, description } = this.state
<Form style={{ marginBottom: "5%", padding: 10 }} onSubmit={ this.handleSubmit } >
<Input label="Name: " name="name" value={name} onChange={handleChange}/>
<Input label="Description: " description="description" value={description} onChange={handleChange}/>
<Button variant="outline-success" size="lg" type="submit" >SUBMIT</Button>
</Form>
}
Advice
Try to avoid manufacturing lambda methods inside the render function as much as possible and have a class property as a lambda method so that lambdas do not need to be manufactured on every render cycle.

ReactNative TextInput not letting me type

For both iOS and Android simulators
The text just disappears/flickers when I start typing. I tried having an initial state of texts with some value instead of keeping it empty. With this the TextInput sticks to this initial state and does not update itself with new text entered.
I think the state is not updating with 'onChangeText' property, but I am not completely sure.
People have seem to solve this, as they had few typos or missing pieces in code. However I have checked mine thoroughly.
Please help if I have missed anything in the below code.
LoginForm.js
import React, { Component } from 'react';
import { Card, Button, CardSection, Input } from './common';
class LoginForm extends Component {
state = { email: '', password: '' }
render() {
return (
<Card>
<CardSection>
<Input
label="Email"
placeHolder="user#gmail.com"
onChangeText={text => this.setState({ email: text })}
value={this.state.email}
/>
</CardSection>
<CardSection>
<Input
secureTextEntry
label="Password"
placeHolder="password"
onChangeText={text => this.setState({ password: text })}
value={this.state.password}
/>
</CardSection>
<CardSection>
<Button>
Log In
</Button>
</CardSection>
</Card>
);
}
}
export default LoginForm;
Input.js
import React from 'react';
import { TextInput, View, Text } from 'react-native';
const Input = ({ label, value, onChangeText, placeholder, secureTextEntry }) => {
const { inputStyle, labelStyle, containerStyle } = styles;
return (
<View style={containerStyle}>
<Text style={labelStyle}>{label}</Text>
<TextInput
secureTextEntry={secureTextEntry}
placeholder={placeholder}
autoCorrect={false}
style={inputStyle}
value={value}
onChangeText={onChangeText}
/>
</View>
);
};
const styles = {
inputStyle: {
color: '#000',
paddingRight: 5,
paddingLeft: 5,
fontSize: 18,
lineHeight: 23,
flex: 2
},
labelStyle: {
fontSize: 18,
paddingLeft: 20,
flex: 1
},
containerStyle: {
height: 40,
flex: 1,
flexDirection: 'row',
alignItems: 'center'
}
};
export { Input };
The only way to solve this was to change the way the values of TextInput fields are updated, with this code below.
value={this.state.email.value}
value={this.state.password.value}
You problem is how the Input component is written.
There is a render function written inside the stateless component which is not a React class component:
const Input = ({ label, value, onChangeText, placeHolder, secureTextEntry }) => ( // ← remove the wrapping parentheses
{
render() { // <--- this should not be here
↑
const { inputStyle, labelStyle, containerStyle } = styles;
return (
<View style={containerStyle} >
<Text style={labelStyle}>{label}</Text>
<TextInput
secureTextEntry={secureTextEntry}
autoCorrect={false}
placeholder={placeHolder}
style={inputStyle}
onChangeText={onChangeText}
value={value}
underlineColorAndroid="transparent"
/>
</View>
);
}
}
);
Change it to this:
const Input = ({ label, value, onChangeText, placeHolder, secureTextEntry }) => {
const { inputStyle, labelStyle, containerStyle } = styles;
return (
<View style={containerStyle} >
<Text style={labelStyle}>{label}</Text>
<TextInput
secureTextEntry={secureTextEntry}
autoCorrect={false}
placeholder={placeHolder}
style={inputStyle}
onChangeText={onChangeText}
value={value}
underlineColorAndroid="transparent"
/>
</View>
);
};
See running example

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