Skip to content
Advertisement

Can’t set state in js react-native

Getting error while trying to setState in React Native.

Code

import React from "react";
import { TextInput, Text, View, Button, Alert } from "react-native";

const UselessTextInput = () => {
  state = { currentDate: "" };

  const setCurentDate = (val) => {
    this.setState({currentDate : val});
  };

  const [value, onChangeText] = React.useState("");

  return (
    <View>
      <Text
        style={{
          alignSelf: "center",
          marginTop: 60,
          fontWeight: "bold",
          fontSize: "25",
        }}
      >
        BirthReminder
      </Text>
      <Text style={{ alignSelf: "center", marginTop: 15, fontSize: 15 }}>
        Enter your friend's birthdate, please
      </Text>
      <TextInput
        clearTextOnFocus={true}
        style={{
          height: 40,
          borderColor: "gray",
          borderWidth: 1,
          marginTop: 20,
          width: 250,
          alignSelf: "center",
        }}
        onChangeText={(value) => setCurentDate(value)}
        value={value}
      />
      <Button title="Add to list"></Button>
    </View>
  );
};

export default UselessTextInput;

Error

TypeError: undefined is not an object (evaluating ‘_this.setState’)

Advertisement

Answer

useState Hook

Functional components don’t have access to setState method but useState hook.

useState hook works by defining the name of value, e.g. foo followed by it’s setter. It’s a convention to name the setter with the same name as that of value with set prefix, i.e. setFoo

const [foo, setFoo] = useState('hi');
// pass the initial value here -^^-

Solution

import { useState } from 'react';
import { TextInput } from 'react-native';

const Component = () => {
  const [value, setValue] = useState('');

  return <TextInput value={value} onChangeText={setValue} />;
};

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement