1

I know I can do this using this.state but I want to make my code uniform. I have both web app and mobile app connected via an API.

This is what my ReactJS Web App looks like (this one works):

import React from 'react'

export default class SignIn extends React.Component {
  signIn = () => {
    var username = this.refs.username.value;
    var password = this.refs.password.value;

    console.log(username); //works
    console.log(password); //works
  }
  render () {
    return (
      <div>
        <input ref='username' placeholder='Username' />
        <input ref='password' type='password' placeholder='Password' />
        <button onClick={this.signIn.bind(this)}>Submit</button>
      </div>
    );
  }
}

The above code does not use any states to get the values of the textboxes and I want to achieve the same thing in React Native.

In my mobile app I have the following code (this doesn't work):

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

export default class App extends React.Component {
  signIn = () => {
    var username = this.refs.username.value;
    var password = this.refs.password.value;

    Alert.alert(username); //doesn't work
    Alert.alert(password); //doesn't work
  }
  render() {
    return (
      <View style={{marginTop: 60}}>
        <TextInput ref='username' placeholder='Username' autoCapitalize='none' />
        <TextInput ref='password' placeholder='Password' autoCapitalize='none' secureTextEntry={true} />
        <Button title='Submit' onPress={this.signIn.bind(this)} />
      </View>
    );
  }
}

I want the code to be uniform as possible but the same logic does not work in React Native. Is it possible to do this without using state?

dcangulo
  • 1,888
  • 1
  • 16
  • 48
  • I am not sure which version of react you use in your Native app but probably instead of string refs, you can try callback refs, `` and use it like `this.username` – Shubham Khatri Oct 24 '18 at 06:46
  • @ShubhamKhatri I'm getting `Reference Error: Can't find variable: ref`. – dcangulo Oct 24 '18 at 06:58

1 Answers1

1

Use this.refs.username._lastNativeText to get the inner text value of the username field.

However, going forward, this is not the best way to do it according to official RN guide. Refer to this SO answer for more details.

Uzair A.
  • 1,586
  • 2
  • 14
  • 30