Home > Back-end >  Cannot get the textinput value from the state
Cannot get the textinput value from the state

Time:06-18

I just started to learn react native. Below is my code


import React, {useState} from 'react';
import { Platform, StyleSheet, Text, TextInput, TouchableOpacity, View, KeyboardAvoidingView, ToastAndroid} from 'react-native';
import Task from './Components/Task'

export default function App() {
  const [task,setTask]=useState();
  const handleAddTask = ()=> {
    console.log(task)
  }
  return (
    <View style={styles.container}>
     <View style={styles.tasksWrapper}>
      <Text style={styles.sectionTitle}>Today's tasks</Text>
      <View style= {styles.items}>
      <Task text={'Task 1'}/>
      <Task text={'Task 2'}/>
      </View>
     </View>
     <KeyboardAvoidingView 
        style={styles.bottomBar}
        behaviour={Platform.OS==='ios'?'padding':'height'} >
      <TextInput style={styles.tastText} placeholder={'Write a Task'} value={task} onChange={text=>setTask(text)}></TextInput>
      <TouchableOpacity style={styles.addButton} onPress={()=>handleAddTask()}>
        <Text style={styles.addText}> </Text>
      </TouchableOpacity>
     </KeyboardAvoidingView >
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'#CCCCFF',
  },
  tasksWrapper:{
    marginTop:50,
    marginLeft:10,
  },
  sectionTitle:{
    fontWeight: 'bold',
    fontSize:24
  },
  items:{
    marginTop:20
  },
  bottomBar:{
    width:'100%',
    position:'absolute',
    bottom:45,
    flexDirection:'row',
    justifyContent:'space-around',
    height:50,
    
  },
  tastText:{
    width:'75%',
    backgroundColor:'white',
    borderRadius:20,
    paddingHorizontal:20

  },
  addButton:{
    borderColor:'black',
    borderWidth:3,
    width:'13%',
    alignItems:'center',  
    padding:7,
    borderRadius: 25
  },
  addText:{
    fontSize:20
  },
});

Task.js Component

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

const Task = (chumma) => {
  return (
    <View style={styles.container}>
      <View style ={styles.styleleft}>
      <View style ={styles.square}></View>
      <Text>{chumma.text}</Text>
      </View>
      <View style ={styles.styleright}>

      </View>
      
    </View>
  )
}

const styles = StyleSheet.create({
  container:{
    width:'95%',
    backgroundColor:'#FFF',
    borderRadius:10,
    padding:15,
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'space-between',
    marginBottom:20
  },
  styleleft:{
    flexDirection:'row',
    alignItems:'center',
    flexWrap:'wrap',
    width:80,
    justifyContent:'space-between',
    
  },
  square:{
    height:20,
    width:20,
    backgroundColor:'#96DED1',
    borderRadius:5,
  },
  styleright:{
    height:13,
    width:13,
    backgroundColor:'white',
    borderWidth:2,
    borderColor:'#87CEEB',
    borderRadius:13,
  },

})
export default Task

When you enter into the TextInput and press TouchableOpacity const handleAddTask = ()=> {console.log(task)} code was supposed to display the value typed in the TextInput field. But when i press TouchableOpacity The console is flooded with the below output

SyntheticEvent {
  "_dispatchInstances": null,
  "_dispatchListeners": null,
  "_targetInst": FiberNode {
    "tag": 5,
    "key": null,
    "type": "RCTView",
  },
  "bubbles": undefined,
  "cancelable": undefined,
  "currentTarget": null,
  "defaultPrevented": undefined,
  "dispatchConfig": Object {
    "phasedRegistrationNames": Object {
      "bubbled": "onTouchEnd",
      "captured": "onTouchEndCapture",
    },
  },
  "eventPhase": undefined,
  "isDefaultPrevented": [Function functionThatReturnsFalse],
  "isPropagationStopped": [Function functionThatReturnsFalse],
  "isTrusted": undefined,
  "nativeEvent": Object {
    "changedTouches": Array [
      [Circular],
    ],
    "identifier": 0,
    "locationX": 39.6220703125,
    "locationY": 38.8785514831543,
    "pageX": 369.44024658203125,
    "pageY": 681.4240112304688,
    "target": 49,
    "targetSurface": -1,
    "timestamp": 50115308,
    "touches": Array [],
  },
  "target": ReactNativeFiberHostComponent {
    "_children": Array [
      ReactNativeFiberHostComponent {
        "_children": Array [
          45,
        ],
        "_internalFiberInstanceHandleDEV": FiberNode {
          "tag": 5,
          "key": null,
          "type": "RCTText",
        },
        "_nativeTag": 47,
        "viewConfig": Object {
          "directEventTypes": Object {
            "topInlineViewLayout": Object {
              "registrationName": "onInlineViewLayout",
            },
            "topTextLayout": Object {
              "registrationName": "onTextLayout",
            },
          },
          "uiViewClassName": "RCTText",
          "validAttributes": Object {
            "accessibilityActions": true,
            "accessibilityHint": true,
            "accessibilityLabel": true,
            "accessibilityLiveRegion": true,
            "accessibilityRole": true,
            "accessibilityState": true,
            "accessibilityValue": true,
            "accessible": true,
            "adjustsFontSizeToFit": true,
            "allowFontScaling": true,
            "android_hyphenationFrequency": true,
            "collapsable": true,
            "dataDetectorType": true,
            "disabled": true,
            "ellipsizeMode": true,
            "importantForAccessibility": true,
            "isHighlighted": true,
            "isPressable": true,
            "maxFontSizeMultiplier": true,
            "minimumFontScale": true,
            "nativeID": true,
            "needsOffscreenAlphaCompositing": true,
            "numberOfLines": true,
            "onAccessibilityAction": true,
            "onAccessibilityEscape": true,
            "onAccessibilityTap": true,
            "onInlineViewLayout": true,
            "onLayout": true,
            "onMagicTap": true,
            "onTextLayout": true,
            "pointerEvents": true,
            "renderToHardwareTextureAndroid": true,
            "selectable": true,
            "selectionColor": true,
            "shouldRasterizeIOS": true,
            "style": Object {
              "alignContent": true,
              "alignItems": true,
              "alignSelf": true,
              "aspectRatio": true,
              "backfaceVisibility": true,
              "backgroundColor": Object {
                "process": [Function processColor],
              },
              "borderBottomColor": Object {
                "process": [Function processColor],
              },
              "borderBottomEndRadius": true,
              "borderBottomLeftRadius": true,
              "borderBottomRightRadius": true,
              "borderBottomStartRadius": true,
              "borderBottomWidth": true,
              "borderColor": Object {
                "process": [Function processColor],
              },
              "borderEndColor": Object {
                "process": [Function processColor],
              },
              "borderEndWidth": true,
              "borderLeftColor": Object {
                "process": [Function processColor],
              },
              "borderLeftWidth": true,
              "borderRadius": true,
              "borderRightColor": Object {
                "process": [Function processColor],
              },
              "borderRightWidth": true,
              "borderStartColor": Object {
                "process": [Function processColor],
              },
              "borderStartWidth": true,
              "borderStyle": true,
              "borderTopColor": Object {
                "process": [Function processColor],
              },
              "borderTopEndRadius": true,
              "borderTopLeftRadius": true,
              "borderTopRightRadius": true,
              "borderTopStartRadius": true,
              "borderTopWidth": true,
              "borderWidth": true,
              "bottom": true,
              "color": Object {
                "process": [Function processColor],
              },
              "decomposedMatrix": true,
              "direction": true,
              "display": true,
              "elevation": true,
              "end": true,
              "flex": true,
              "flexBasis": true,
              "flexDirection": true,
              "flexGrow": true,
              "flexShrink": true,
              "flexWrap": true,
              "fontFamily": Object {
                "process": [Function processFontFamily],
              },
              "fontSize": true,
              "fontStyle": true,
              "fontVariant": true,
              "fontWeight": true,
              "height": true,
              "includeFontPadding": true,
              "justifyContent": true,
              "left": true,
              "letterSpacing": true,
              "lineHeight": true,
              "margin": true,
              "marginBottom": true,
              "marginEnd": true,
              "marginHorizontal": true,
              "marginLeft": true,
              "marginRight": true,
              "marginStart": true,
              "marginTop": true,
              "marginVertical": true,
              "maxHeight": true,
              "maxWidth": true,
              "minHeight": true,
              "minWidth": true,
              "opacity": true,
              "overflow": true,
              "overlayColor": Object {
                "process": [Function processColor],
              },
              "padding": true,
              "paddingBottom": true,
              "paddingEnd": true,
              "paddingHorizontal": true,
              "paddingLeft": true,
              "paddingRight": true,
              "paddingStart": true,
              "paddingTop": true,
              "paddingVertical": true,
              "position": true,
              "resizeMode": true,
              "right": true,
              "rotation": true,
              "scaleX": true,
              "scaleY": true,
              "shadowColor": Object {
                "process": [Function processColor],
              },
              "shadowOffset": Object {
                "diff": [Function sizesDiffer],
              },
              "shadowOpacity": true,
              "shadowRadius": true,
              "start": true,
              "textAlign": true,
              "textAlignVertical": true,
              "textDecorationColor": Object {
                "process": [Function processColor],
              },
              "textDecorationLine": true,
              "textDecorationStyle": true,
              "textShadowColor": Object {
                "process": [Function processColor],
              },
              "textShadowOffset": true,
              "textShadowRadius": true,
              "textTransform": true,
              "tintColor": Object {
                "process": [Function processColor],
              },
              "top": true,
              "transform": Object {
                "process": [Function processTransform],
              },
              "transformMatrix": true,
              "translateX": true,
              "translateY": true,
              "width": true,
              "writingDirection": true,
              "zIndex": true,
            },
            "testID": true,
            "textBreakStrategy": true,
          },
        },
      },
    ],
    "_internalFiberInstanceHandleDEV": FiberNode {
      "tag": 5,
      "key": null,
      "type": "RCTView",
    },
    "_nativeTag": 49,
    "viewConfig": Object {
      "Commands": Object {
        "hotspotUpdate": 1,
        "setPressed": 2,
      },
      "NativeProps": Object {
        "accessibilityActions": "Array",
        "accessibilityHint": "String",
        "accessibilityLabel": "String",
        "accessibilityLabelledBy": "mixed",
        "accessibilityLiveRegion": "String",
        "accessibilityRole": "String",
        "accessibilityState": "Map",
        "accessibilityValue": "Map",
        "accessible": "boolean",
        "alignContent": "String",
        "alignItems": "String",
        "alignSelf": "String",
        "aspectRatio": "number",
        "backfaceVisibility": "String",
        "backgroundColor": "Color",
        "borderBottomColor": "Color",
        "borderBottomEndRadius": "number",
        "borderBottomLeftRadius": "number",
        "borderBottomRightRadius": "number",
        "borderBottomStartRadius": "number",
        "borderBottomWidth": "number",
        "borderColor": "Color",
        "borderEndColor": "Color",
        "borderEndWidth": "number",
        "borderLeftColor": "Color",
        "borderLeftWidth": "number",
        "borderRadius": "number",
        "borderRightColor": "Color",
        "borderRightWidth": "number",
        "borderStartColor": "Color",
        "borderStartWidth": "number",
        "borderStyle": "String",
        "borderTopColor": "Color",
        "borderTopEndRadius": "number",
        "borderTopLeftRadius": "number",
        "borderTopRightRadius": "number",
        "borderTopStartRadius": "number",
        "borderTopWidth": "number",
        "borderWidth": "num...(truncated to the first 10000 characters)

Can anyone explain to me what the problem is?

CodePudding user response:

Change this line:

onChange={text=>setTask(text)

to

onChangeText={text=>setTask(text)

onChange type is ({ nativeEvent: { eventCount, target, text} }) => void, That is why it prints that log. Whereas onChangeText passes the changed text.

CodePudding user response:

Are you looking to log what the user entered into the TextInput or simply that the button is functional?

If you want to check the button is working as intended simply put:

  const handleAddTask = ()=> {
    console.log("Button Pressed!")
  }

If you're looking to get back what the user entered you can use:

     <KeyboardAvoidingView 
        style={styles.bottomBar}
        behaviour={Platform.OS==='ios'?'padding':'height'} >
      <TextInput 
        style={styles.tastText} 
        placeholder={'Write a Task'} 
        value={task} 
        onSubmitEditing = {( value ) => setTask(value.nativeEvent.text)}
        onChangeText={text=>setTask(text)}></TextInput>
      <TouchableOpacity style={styles.addButton} onPress={()=>handleAddTask()}>
        <Text style={styles.addText}> </Text>
      </TouchableOpacity>
     </KeyboardAvoidingView >
     <View>
     //add this line
     <Text>{task}</Text>
     </View>

This isn't the prettiest way to do it, but it's super easy (adding one line of code). What this will do is as the user is typing it will show on the screen what they are entering.

Example here

  • Related