TextInput focus blurring when first clicked - react-native

There was no issue before I tried to implement the handleInputBlur and handleInputFocus functions (Used to change the background when in focus). When I first click on the TextInput it comes into focus, but then immediately blurs, resulting in the background flashing then disappearing. What's strange is that after this first click, the future clicks work absolutely fine, focusses and blurs as it should. I do not understand why on the initial click/focus it immediately blurs. Code below:
EDIT: Bit more context, it's inside of a modal, which contains multiple of these editable items.
class EditableItem extends Component {
constructor(props) {
super(props)
const { value } = this.props
this.state = {
value,
isFocused: null,
}
}
handleInputBlur = () => {
this.setState({ isFocused: false })
console.log('blurring')
}
handleInputFocus = () => {
this.setState({ isFocused: true })
console.log('focussing')
}
render() {
const { name, secure, children, autoCapitalize } = this.props
const { value, isFocused } = this.state
const multiline = !secure
return (
<View>
<View style={styles.container}>
<Text style={styles.name}>{name}</Text>
<View style={isFocused ? styles.activeBackground : styles.unfocusedBackground}>
<TextInput
placeholder={name}
placeholderTextColor={COLOR_BASE_3}
underlineColorAndroid="transparent"
style={styles.value}
secureTextEntry={secure}
value={value}
// blurOnSubmit
onSubmitEditing={() => {
Keyboard.dismiss()
}}
returnKeyType="done"
keyboardAppearance="dark"
autoCapitalize={autoCapitalize}
onChangeText={this.onChange}
multiline={multiline}
onBlur={() => this.handleInputBlur()}
onFocus={() => this.handleInputFocus()}
/>
{children}
</View>
</View>
<View style={styles.divider} />
</View>
)
}
onChange = value => {
const { onChange } = this.props
this.setState({ value })
onChange(value)
}
}

Ok so solved this by setting autofocus to true in the TextInput. Not sure why not having this set causes this issue but it's a solution regardless.

Related

React Native Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state

Im learning react native, and i try to use state, now im facing an issue "Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state."
Here my code
class Quantity extends React.Component {
constructor(props) {
super(props);
this.state = {
qty:1
};
this.setQty = this.setQty.bind(this);
}
setQty = (e) =>{
this.setState({
qty:e,
});
}
componentDidMount() {
this.props.onRef(this)
this.state.qty = 1
}
componentWillUnmount() {
this.props.onRef(undefined)
}
getCheckoutQty() {
return this.state.qty.toString();
}
minusQty = () => {
let newQty = this.state.qty -1;
this.setQty(newQty)
}
plusQty = () => {
let newQty = this.state.qty +1;
this.setQty(newQty);
}
render() {
const {qty}=this.state
return (
<View style={styles.row}>
<TouchableOpacity style={styles.icon}
disabled={(this.state.qty==1)?true:false}
// onPress={() => this.minusQty()}
>
<Icon name="minus" color="#000" style={(this.state.qty==1)?{opacity:0.2}:{opacity:1}}/>
</TouchableOpacity>
<Input
style={styles.qtyBox}
keyboardType="numeric"
returnKeyType="done"
value={qty.toString()}
onChangeText={(e)=>this.setQty(this)}
/>
<TouchableOpacity style={styles.icon}
// onPress={() => this.plusQty()}
>
<Icon name="plus" color="#000" />
</TouchableOpacity>
</View>
);
}
}
any way to fix it?
Thank for the support

How can I hide/show components by touching not button but screen on React Native?

I'm learning React Native for the first time. I want to implement a function to show/hide the component by touching the screen, not a specific button.
(Please check the attached file for the example image.)
enter image description here
In this code, I've tried to make a function. if I touch the screen (<View style={style.center}>, then show/hide the renderChatGroup() and renderListMessages() included in <View style={style.footer}>. The source code is below.
In my code, it works. However, the two <View> tag is not parallel. the footer view is center View's child.
I want to make them parallel. but I couldn't find the contents about controlling another <View> tag, not a child. In this code, I used setState, then I couldn't control another the below <View>.
Of course, I tried Fragment tag, but it didn't render anything.
How could I do implement this function? Please help me!
export default class Streamer extends React.Component {
constructor(props) {
super(props);
this.state = {
isVisibleFooter: true,
};
}
renderChatGroup = () => {
const { isVisibleFooter } = this.state;
if (isVisibleFooter) {
return (
<ChatInputGroup
onPressHeart={this.onPressHeart}
onPressSend={this.onPressSend}
onFocus={this.onFocusChatGroup}
onEndEditing={this.onEndEditing}
/>
);
}
return null;
};
onPressVisible = () => {
const { isVisibleFooter } = this.state;
this.setState(() => ({ isVisibleFooter: !isVisibleFooter }));
};
render() {
return (
<SafeAreaView style={styles.container}>
<SafeAreaView style={styles.contentWrapper}>
<View style={styles.header} />
<TouchableWithoutFeedback onPress={this.onPressVisible}>
<View style={styles.center}>
<View style={styles.footer}>
{this.renderChatGroup()}
{this.renderListMessages()}
</View>
</View>
</TouchableWithoutFeedback>
</SafeAreaView>
</SafeAreaView>
);
}
}
Firstly I would highly recommend you use react native with functional components and React Hooks as they alternative will soon will be deprecated.
Since onPress is not available on the View Component, you would need to replace it with TouchableWithoutFeedback as you have already done in your code.
For Showing/Hiding a view you would need to use a conditional operator.
export default class Streamer extends React.Component {
constructor(props) {
super(props);
this.state = {
isVisibleFooter: true,
};
}
renderChatGroup = () => {
const { isVisibleFooter } = this.state;
if (isVisibleFooter) {
return (
<ChatInputGroup
onPressHeart={this.onPressHeart}
onPressSend={this.onPressSend}
onFocus={this.onFocusChatGroup}
onEndEditing={this.onEndEditing}
/>
);
}
return null;
};
onPressVisible = () => {
this.setState(() => ({ isVisibleFooter: !isVisibleFooter }));
const { isVisibleFooter } = this.state;
};
render() {
return (
<SafeAreaView style={styles.container}>
<SafeAreaView style={styles.contentWrapper}>
<View style={styles.header} />
<TouchableWithoutFeedback onPress={this.onPressVisible}>
<View style={styles.center}>
{isVisibleFooter && <View style={styles.footer}>
{this.renderChatGroup()}
{this.renderListMessages()}
</View>}
</View>
</TouchableWithoutFeedback>
</SafeAreaView>
</SafeAreaView>
);
}
}
Here you can see i have replaced
<View style={styles.footer}>
{this.renderChatGroup()}
{this.renderListMessages()}
</View>
with
{isFooterVisible && <View style={styles.footer}>
{this.renderChatGroup()}
{this.renderListMessages()}
</View>}
stating that to only display the Footer View when
const isFooterVisible = true;

Edit state of every item of a FlatList

I made a page in which I use a FlatList. This FlatList uses an item component I made that display another view below itself when pressed by setting a state "hidden" to false. The main issue I have is that I can't find a way to change the "hidden" state to true when one of the item is pressed, hence always keeping only 1 item displaying the additional view at the time. In the same time, when I refresh/re-render my FlatList, it does not set all the "hidden" state back to true.
This is where I render my FlatList
_onRefresh() {
this.setState({refreshing: true}, () => this._loadList());
}
render() {
return (
<View style={[style.container, style.whiteBackground]}>
<CategoryFilter filterCallback={this._changeCategory}/>
<FlatList
data={this.state.list}
extraData={this.state}
renderItem={({item}) =>
<ListItemComponent item={item} category={this.state.category}/>
}
refreshing={this.state.refreshing}
onRefresh={() => this._onRefresh()}
/>
</View>
);
}
And this is where I render and display the hidden view
constructor(props) {
super(props);
this.state = {
hidden: true
};
}
componentDidMount() {
this.setState({hidden: true});
}
_onPress() {
this.setState({
hidden: !this.state.hidden
});
}
[...]
_renderOS(item) {
if (Platform.OS === 'android') {
return (
<TouchableNativeFeedback onPress={() => this._onPress()}>
{this._renderItem(item)}
</TouchableNativeFeedback>
);
} else if (Platform.OS === 'ios') {
return(
<TouchableOpacity onPress={() => this._onPress()}>
{this._renderItem(item)}
</TouchableOpacity>
);
}
}
[...]
_renderDescription(item) {
if (this.state.hidden === true) {
return null;
} else {
return (
<View style={listItemStyle.descriptionContainer}>
<Text style={listItemStyle.description}>
{item.description}
</Text>
</View>
);
}
}
I just want to be able to have only one of the list item with hidden set to false at the time and have said item to be set to hidden=true when the page is refreshed, but I never found anything that could help me.
So after thinking a lot I finally found a solution.
Instead of handling the hidden state in every item, I made a list of every hidden state associated to the items ids in the component where my flatlist is, adding a function that will set the previously opened item to hidden and open the new one, and passing it as a callback to my items so that it can be called when I press them.
_onPress(id) {
let items;
items = this.state.items.map((item) => {
if (item.id === this.state.openId)
item.open = false;
else if (item.id === id)
item.open = true;
return item;
});
this.setState({
items: items,
openId: (id === this.state.openId ? '' : id)
});
}
<FlatList
data={this.state.items}
extraData={this.state}
renderItem={({item}) =>
<ListItemComponent
onPress={this._onPress.bind(this)}
bet={item}
categoryList={this.state.categoryList}
open={item.open}/>
}
refreshing={this.state.refreshing}
onRefresh={() => this._onRefresh()}
/>

onChangeText setState only sets one character not the whole string

I accept text input from a search bar and setState to text but its only one character at a time how can I continue to update and add to the state rather than replace what's in state? I feel like this is the intended action but my code does not do this.
class FindRecipesScreen extends Component {
static navigationOptions = {
title: "Find Recipes",
header: null
};
constructor(props) {
super(props);
this.state = {
search: "",
recipe: "",
text: "",
};
}
backToHomePage = () => {
this.props.navigation.navigate("Home");
};
componentDidMount() {
this.props.getRecipeList(this.props.auth.jwt);
}
handleSearch = text => {
console.log("text", text);
this.setState({text: text});
};
render() {
return (
<View style={styles.recipe}>
<View style={styles.recipeBar}>
<ActionNavbar title="Find Recipes"
leftAction={this.backToHomePage}
leftIcon={require("app/assets/icons/cancel.png")}
rightAction={this.backToHomePage}
rightIcon={require("app/assets/icons/filter.png")}/>
</View>
<View>
<View>
<SearchBar
containerStyle={styles.searchContainer}
inputContainerStyle={styles.searchInputContainer}
inputStyle={styles.searchInput}
lightTheme
searchIcon={searchIcon}
round
onChangeText={this.handleSearch}
placeholder="Search Cookbooks"
/>
<View style={styles.forward}>
<Image
style={styles.forwardIcon}
width={18}
height={18}
source={require("app/assets/icons/forward.png")}
/>
</View>
</View>
</View>
</View>
);
}
}
I found the solution... I needed const { search } = this.state; after render but before return with searcher
Use debouncer in the handleSearch function so the state is set after your debounce time.

how to input get focus every time in react navigation

I use react navigation TabNavigator and I want every time user goes to second tab, one TextInput in screen get focus and keyboard gets popup
You can use refs and react navigation lifecycle for this:
constructor(props) {
super(props);
this.input = React.createRef();
this.didFocusDSubscription = this.props.navigation.addListener(
'didFocus',
payload => {
this.input.current.focus();
}
);
}
render() {
return <TextInput ref={this.input} />;
}
this might help you
this.viewDidAppearListener = this.props.navigation.addListener('didFocus', (payload) => this._viewDidAppear(payload));
didFocus event will be triggered every time the view is showed (like viewDidAppear in iOS) so you can then do focus() on your textinput manually.
Simplest is to add "autoFocus" to your textInput
Like this:
<TextInput
placeholder="Type any activity name"
placeholderTextColor="lightgray"
...
ref="textInput"
autoFocus />
For react-navigation#3.X.X use navigation.addListener and .focus():
class AutoFocusedTextInput extends React.Component {
state = {
text: '',
}
componentDidMount() {
this.props.navigation.addListener('didFocus', payload => {this.textInput.focus()})
}
componentWillUnmount() {
didFocusSubscription.remove();
}
render() {
return (
<View>
<TextInput
ref={(component) => this.textInput = component}
autoFocus={true}
placeholder="Start typing"
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
</View>
)
}
}
The reference:
https://reactnavigation.org/docs/3.x/navigation-prop#addlistener---subscribe-to-updates-to-navigation-lifecycle