ru ku
ru ku

Reputation: 41

How to call function on 'Enter' press in TextInput - React Native

I am trying to make Search Bar. I want user to type something in TextInput and when user press 'Enter' I want to call my function.

<TextInput
//here when user press enter call function()
style={styles.searchStyle}
allowFontScaling={false}
placeholder="Search" 
onChangeText={(val) => {setSearch(val)}}
/> 

I tried onSubmitEditing but it doesn't work.

Upvotes: 3

Views: 6177

Answers (2)

Alok Singh
Alok Singh

Reputation: 181

import React, { Component } from 'react' import {TextInput} from 'react-native'

const Trial =()=>{
    const onSubmitted=()=>{
        console.log('Submitted')
      }
return(
    <TextInput
//here when user press enter call function()
// style={styles.searchStyle}
allowFontScaling={false}
placeholder="Search" 
onSubmitEditing={()=>onSubmitted()}

/>
)
}

export default Trial

onSubmitEditing it works fine, I hope it would be helpful for you

Upvotes: 8

Nikhil bhatia
Nikhil bhatia

Reputation: 1397

if you are using mutiline={true} in TextInput like <TextInput multiline={true} /> onSubmitEditing will not work, instead it will move to nextLine.

I am doing a workaround, so basically I check if user entered next line, if so, call submit function and dismiss keyboard, you can import {Keyboard} from react-native

<TextInput onChangeText={(txt) => {
        if (/\n/.test(txt)) {
         //call submit function here
          Keyboard.dismiss()
          return
        } else {
          //do something here
        }
        
      }} />

Upvotes: 0

Related Questions