How to focus TextInput after component mount ( initialize with the TextInput focused ) - React Native - react-native

How do I open a stateless component with the TextInput already in foucs?
Thank you all!

Hi TĂșlio here is the code and you can also check the live working example I've added in this link --> Snack Example
export default function App() {
const focusRef = React.useRef()
React.useEffect(() => {
if (focusRef.current) focusRef.current.focus()
},[focusRef])
return (
<View style={styles.container}>
<TextInput
placeholder="FirstTextInput"
returnKeyType="next"
ref={focusRef}
blurOnSubmit={false}
style={{padding:10}}
/>
</View>
);
}

If you only want the TextInput field focused on component mount, then you can use the autoFocus prop of a TextInput component
e.g.
<TextInput
autoFocus={true}
/>

Related

How to pass method to this.props.children in REACT NATIVE?

I need to pass a method from parent to child component via {this.props.children} in react native.
i tried
{React.cloneElement(this.props.children, { lang: "en" })}
but it just giving an error. any idea on how to do this in react native ?
export default function ComponentA(props){
return(
<View style={{backgroundColor: "red"}}>
{props.children}
</View>
);
};
<ComponentA>
<Text>THIS TEXT WILL HAVE A RED BACKGROUND</Text>
</ComponentA>

One form, but different state

I'm moving now from other technologies to React Native and I have a problem. I have one presentational component which is <TaskInput />.
const TaskInput = (props: ITaskInputProps) => {
return (
<View style={styles.container} >
<Text style={styles.title}>{props.title}</Text>
<TextInput
style={styles.input}
multiline
scrollEnabled={false}
/>
</View>
)
}
ParentComponent over TaskInput
import React from 'react';
import { View } from 'react-native';
import styles from './styles';
import TaskInputContainer from '../task-input';
interface ITaskConfigurationProps {
title: string,
isInputForm?: boolean,
isRequired?: boolean,
}
const TaskConfiguration = (props: ITaskConfigurationProps) => {
return (
<View style={(props.isRequired) ? [styles.container, {backgroundColor: '#f25e5e'}] : styles.container}>
{ props.isInputForm && <TaskInputContainer title={props.title} /> }
</View>
);
}
export default TaskConfiguration;
const TaskScreen = (props: ITaskScreenProps) => {
return (
<View style={styles.container}>
<SectionTitle title={'Task Settings'} />
<ScrollView contentContainerStyle={styles.configurations}>
<TaskConfiguration title={"What you need to do?"} isInputForm={true} isRequired={true} />
<TaskConfiguration title={"Description"} isInputForm={true} />
<TaskConfiguration title={"Deadline"} />
<TaskConfiguration title={"Priority"} />
</ScrollView>
<Button isDone={true} navigation={props.navigation} />
</View>
)
}
TaskInput component takes one prop which is title and it will be in two places on my screen. One component will be called "Enter main task", another one is "Description". But this component will accept different states like currentMainTextInput and currentDescriptionTextInput. This is my idea of re-usable component TextInput, but I can't do what I want because if I set type in one input - other input will re-render with first input (both of them are one presentational component).
I want to use this dumb component in any place of my app. I don't want to create a new identical component and duplicate code, How can I do that? (P.S. I was thinking about "redux or class/hooks", but what should I use...)

how to setup Onpress On Textinput in react-native

I am developing an app on react native. I want to call a date picker when i press on a Text-Input and after selecting a date it should show on the Text-Input
Wrap TextInput into a view and set pointerEvents as none.
Now you can use Pressable component from react-native to listen to the onpress event.
<Pressable onPress={() => alert('Hi!')}>
<View pointerEvents="none">
<TextInput />
</View>
</Pressable>
You cannot explicitly call onPress for TextInput. You could only use. onFocus which will be called when you press the input box to get cursor over there. No need to focus on onBlur as your use case doesn't required.. Handle close within onFocus if possible.
onFocus = () => {
// do something
}
render() {
<TextInput onFocus={onFocus} />
}
What you have to do is use onFocus and onBlur of TextInput.
<TextInput
onFocus={this.onFocus}
onBlur={this.onBlur}
/>
onFocus = () => {
// Open date picker
}
onBlur = () => {
// Close date picker and add value to textinput
}
You can make text input field read only by providing
editable={false}
pointerEvents="none"
prop to TextInput.
Wrap TextInput inside View and set pointerEvents="none", wrap that view with TouchableOpacity or any other Touchable Component. Please see below example!
<TouchableOpacity
onPress={() => {
alert('hello');
}}>
<View pointerEvents="none">
<TextInput
onChange={() => {}}
value={''}
placeholder={waterMark}
editable={!isDisabled}
selectTextOnFocus={!isDisabled}
/>
</View>
</TouchableOpacity>

React native disable submit keyboard on device if text input is empty string

Like a title, I want to disable a submit button (Search) on device's keyboard if text input is an empty string.
I creating a search bar and using TextInput.
How can I do this?
you should have 2 state (textSearch and buttonStatus) and check every onChangeText in TextInput props
here's a simple code I've used:
import React, {Component} from 'react';
import RN, {View, StyleSheet, Text} from 'react-native';
export default class History extends Component {
constructor(props) {
super(props);
this.state={
search:null,
disabledButton:true
}
}
render(){
return(
<View style={styles.container}>
<RN.TextInput
value={this.state.search}
onChangeText={(e)=>{
this.setState({search:e, disabledButton:e==""?true:false})
}}
/>
<RN.Button
title="Search"
disabled={this.state.disabledButton}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container:{flex:1, justifyContent:'center', alignItems:'center'}
})
this is the first time I've provided help here, so hopefully it helps someone.
The inputText should be whatever state you use to store your text.
addItem() is whatever function name you want to execute when there are enough characters.
I wanted to require the user to type more than 1 character, so adjust to your liking.
onSubmitEditing={() => {(inputText.length < 2) ? console.log('test') : addItem()}}
<TextInput
style={styles.input}
onSubmitEditing={() => {
(inputText.length < 2) ? console.log('test') : addItem()
}}
maxLength={20}
autoCorrect={false}
onChangeText={onChangeText}
placeholder={'Scavenger Hunt Item'}
value={inputText}>
</TextInput>

How to programmatically select text in a TextInput component

Is there a way to programmatically highlight/select text that is inside a TextInput component?
You can use selectTextOnFocus to achieve this. This will ensure that all text inside the TextInput is highlighted when the field is tapped into.
Actually you can, by accessing textInput's method by refs.
<TextInput ref={input => this.myInput = input} selectTextOnFocus style={{height: 100, width: 100}} defaultValue='Hey there' />
and where you want to select all text programmatically you can
this.myInput.focus()
works on iOS, not sure about android.
Reference : http://facebook.github.io/react-native/releases/0.45/docs/textinput.html#selectionstate
I don't know if there's a better way, but I found a workaround. The text has to be focused first. Here's an example
import React { Component } from 'react';
import { Button, TextInput, findNodeHandle } from 'react-native';
import TextInputState from 'react-native/lib/TextInputState';
class MyComponent extends Component {
render() {
return (
<View style={{ flex: 1, }}>
<Button
title="select text"
onPress={() => {
TextInputState.focusTextInput(findNodeHandle(this.inputRef))
}}
</
<TextInput
selectTextOnFocus
ref={ref => this.inputRef = ref}
/>
</View>
);
}
}
I'm here to share my findings. In a List, you might encounter that selectTextOnFocus is broken. In this case you can use this method selection. From React-Native I found this:
In my case I had trouble with the selectTextOnFocus prop in a list. So I had to add a debounce function to work with selection prop.
const [shouldSelect, setShouldSelect] = useState(undefined);
const onFocus = () =>{
setShouldSelect({start:0, end:String(text).length});
}
const focus = useCallback(_.debounce(onFocus,500),[shouldSelect]);
<TextInput
selection={shouldSelect}
onBlur={()=>setShouldSelect(undefined)}
onFocus={()=>focus()}// this is important
selectTextOnFocus
ref={r=>onRef(r)}
keyboardType={'number-pad'}
autoCorrect={false}
blurOnSubmit={false}
returnKeyType={'done'}
underlineColorIos={'transparent'}
underlineColorAndroid={'white'}
allowFontScaling={false}
value={String(text)}
/>
this.inputRef.focus() sets focus to the TextInput component, and then the flag you set in the attributes selectTextOnFocus does the rest.
Note: For those who wants to use selectTextOnFocus short answer. Actually, it works fine in IOS, but doesn't work in Android.
Thanks to Arnav Yagnik; Following is a similar approach in a functional component:
const inputRef = React.useRef(null);
React.useEffect(() => {
if (inputRef.current) {
console.log('focusing !');
inputRef.current.focus();
}
}, []);
return <TextInput
multiline
label="Amount"
selectTextOnFocus
placeholder="Write Count"
value={stockCount.toString()}
/>