Search code examples
javascriptreact-nativeonchangeuse-state

global onChange handler in react native


I'm trying to create a global onchange handler in react-native but it's not setting the value of my email and password to whatever i typed in i have tried searching on google but most example are based on react.js not react-native i will appreciate immediate help

import React, {useState} from 'react';
import {View, Text, Button, TextInput} from 'react-native';
import style from './Style';

export default function Login() {
  const [authDetails, setAuthDetails] = useState({
    email: '',
    password: '',
  });

  const {email, password} = authDetails;

  const onChange = text =>
    setAuthDetails({
      ...authDetails,
      email: text.email,
      password: text.name,
    });
  const login = () => {
    console.log('EMAIL=', email, '\n', 'password =', password);
  };

  return (
    <View>
      <TextInput
        name="email"
        placeholder="Email"
        onChangeText={onChange}
        value={email}
      />

      <TextInput
        name="password"
        placeholder="Password"
        onChangeText={onChange}
        value={password}
      />
      <Button title="Login" onPress={login} />
    </View>
  );
}

Solution

  • the way you have may be fixed as follows:

    import React, {useState} from 'react';
    import {View, Text, Button, TextInput} from 'react-native';
    import style from './Style';
    
    export default function Login() {
      const [authDetails, setAuthDetails] = useState({
        email: '',
        password: '',
      });
    
      const {email, password} = authDetails;
    
      const onChange = update =>
        setAuthDetails({
          ...authDetails,
          ...update
        });
      const login = () => {
        console.log('EMAIL=', email, '\n', 'password =', password);
      };
    
      return (
        <View>
          <TextInput
            name="email"
            placeholder="Email"
            onChangeText={text => onChange({ email: text }) }
            value={email}
          />
    
          <TextInput
            name="password"
            placeholder="Password"
            onChangeText={text => onChange({ password: text }) }
            value={password}
          />
          <Button title="Login" onPress={login} />
        </View>
      );
    }
    

    As you can see from the above code onChangeText hook invokes the function with new text value of the element that calls it, therefore we still have to differentiate between what param to update in the state.