Home > Back-end >  React native - how to detect space press on keyboard?
React native - how to detect space press on keyboard?

Time:05-16

I am building a chat app and trying to count how many times the user pressed on 'space' key every time they press it and not counting it on the final outcome of their textinput entery.

<TextInput onKeyPress={(e) => {
    let pressedKey = e.nativeEvent.key;
    if(pressedKey === ' '){
    pressedKey = 'Space';
  } />

This code example works for me only if the user press two times on space

CodePudding user response:

Here is the code that do the count for you:

import React, {useState} from 'react';
import {StyleSheet, Text, View, TextInput} from 'react-native';

const App = () => {
  const [spaceCount, setSpaceCount] = useState(0);
  const onInputKeyPressHandler = e => {
    e.nativeEvent.key === ' ' &&
      setSpaceCount(oldSpaceCount => oldSpaceCount   1);
  };
  return (
    <View style={styles.container}>
      <Text>Hello friend :)</Text>
      <TextInput style={styles.input} onKeyPress={onInputKeyPressHandler} />
      <Text>{`Space Count: ${spaceCount}`}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingTop: 100,
    paddingHorizontal: 30,
  },
  input: {
    height: 50,
    borderWidth: 1,
    marginVertical: 10,
    paddingHorizontal: 20,
  },
});

export default App;

enter image description here

CodePudding user response:

try using a counter useState. when the user presses on space, the counter increments by 1

    const [spaceCounter, setSpaceCounter] = useState(0)

<TextInput onKeyPress={(e) => {let pressedKey = e.nativeEvent.key;
    if(pressedKey === ' ')
{
    pressedKey = 'Space';
    setSpaceCounter = spaceCounter  1;` 
  }/>
  • Related