smilada
smilada

Reputation: 17

How can I store and manipulate text input upon pressing enter?

I am trying to store text input upon pressing enter which is not working for me. Not even an alert goes off when I press enter.

Here is my current simplified code:

const ToDo = () => {
  const saveValueFunction = (e: any) => {
    console.debug(e.keyCode)
    if (e.keyCode === 13) {
      AsyncStorage.setItem('any_key_here', e)
      alert('Data Saved')
    }
  }

  const [value, onChangeText] = React.useState('')
  return (
    <TextInput
      placeholder="Add a Task"
      placeholderTextColor="aqua"
      color="aqua"
      backgroundColor="#262626"
      style={styles.textInput}
      onChange={(e) => onChangeText(e.target.value)}
      value={value}
      onKeyDown={(e) => saveValueFunction(e)}
    />
  )
}

Upvotes: 1

Views: 672

Answers (3)

Nidhin
Nidhin

Reputation: 1

Just use onSubmitEditing={} prop in text input and call the save function inside the curly brackets.

Upvotes: 0

Ajeet Shah
Ajeet Shah

Reputation: 19813

You can use onKeyPress which is called when any key is pressed. It is called with Native event which has key property which holds values like Enter, Backspace or the character typed by the user. So you can compare it with Enter to detect the Enter pressed by the user.

const [value, setValue] = React.useState('');
const handleKeyPress = e => {
  if (e.key === 'Enter') {
    AsyncStorage.setItem('any_key_here', value);
    setValue('');
    showAlert();
    alert(`Task saved: ${value}`);
  }
};

<TextInput
  value={value}
  onChangeText={text => setValue(text)}
  onKeyPress={e => handleKeyPress(e)}
  placeholder="Add a Task"
  placeholderTextColor="aqua"
  color="aqua"
  backgroundColor="pink"
  style={styles.textInput}
/>

Code Playground: Expo

Upvotes: 1

isa_toltar
isa_toltar

Reputation: 594

const [inputData, setInputData] = useState('');
const [includeds, setIncludeds] = useState([]);

 const handleChange = (e: any) => {
    setInputData(e.target.value);
  };

const onKeyPressEvent = (e: any) => {
      if (e.key === 'Enter') {
        if (
          includeds &&
          includeds.length < MAX_INCLUDES &&
          (inputData && inputData.length !== 0)
        ) {
          e.persist();
          setIncludeds(arr => [...arr, inputData]);
          setInputData('');
        }
      }
    }


return(
         <input
          onChange={e => handleChange(e)}
          onKeyDown={e => onKeyPressEvent(e)}
        />
 )

You can basically do something like this.You should implement your case on top of this code.

Upvotes: 0

Related Questions