Pass ref as function parameter React Native
In the current code, I use ref to change TextInput
the style of a component that uses a function in a method setNativeProps
.
class RegisterScreen extends Component {
constructor(props) {
super (props)
this.state = {
borderBottomStyle: '#f7f7f7'
}
}
focusedInput = () => {
this.textInput.setNativeProps({
style: { borderBottomColor: '#445AE3' }
})
}
blurredInput = () => {
this.textInput.setNativeProps({
style: { borderBottomColor: '#f7f7f7' }
})
}
render() {
return (
<View style={styles.container} >
<View style={styles.form}>
<TextInput
ref={c => { this.textInput = c}}
style={styles.textInput}
onFocus={this.focusedInput}
onBlur={this.blurredInput}
style={[styles.formInput, { borderBottomColor: this.state.borderBottomStyle }]}
placeholder={"Email"}
/>
<TextInput
style={[styles.formInput, { borderBottomColor: this.state.borderBottomStyle }]}
placeholder={"Password"}
/>
</View>
</View>
)
}
}
export default RegisterScreen
It's compatible with my first one, TextInput
but I'm looking for a way to do the same with the second one. I first thought of passing a ref to the focusedInput
and blurredInput
function as a parameter to specify the element to modify, but I'm not very familiar with refs.
Is there a way to achieve this?
thank you for your help
If I understand your question correctly, you want to conditionally change the UI of the textbox based on whether or not the focus is on.
You can use just one state to keep the currentFocused textInput name and conditionally change the UI of the textbox based on the currentFocused box.
I did a quick demo on sandbox. Please see the link below.
import React, { Component } from "react";
import { View, TextInput } from "react-native";
class RegisterScreen extends Component {
constructor(props) {
super(props);
this.state = {
borderBottomStyle: "#f7f7f7",
currentlyFocused: null
};
}
focusedInput = () => {
this.textInput.setNativeProps({
style: { borderBottomColor: "#445AE3" }
});
};
blurredInput = () => {
this.textInput.setNativeProps({
style: { borderBottomColor: "#f7f7f7" }
});
};
render() {
return (
<View style={{ flex: 1 }}>
<View>
<TextInput
style={{
borderBottomColor:
this.state.currentlyFocused === "email" ? "red" : "grey",
borderStyle: "solid",
borderWidth: this.state.currentlyFocused === "email" ? 3 : 0,
height: 50,
marginTop: 20
}}
onFocus={() => this.setState({ currentlyFocused: "email" })}
onBlur={() => this.setState({ currentlyFocused: "" })}
placeholder={"Email"}
/>
<TextInput
style={{
borderBottomColor:
this.state.currentlyFocused === "password" ? "red" : "grey",
borderStyle: "solid",
borderWidth: this.state.currentlyFocused === "password" ? 3 : 0,
height: 50,
marginTop: 20
}}
onFocus={() => this.setState({ currentlyFocused: "password" })}
onBlur={() => this.setState({ currentlyFocused: "" })}
placeholder={"Password"}
/>
</View>
</View>
);
}
}
export default RegisterScreen;