Getting the value from input fields in React Native

Almost everyone does it wrong, they pass the value to a state, this is very similar to how Angular and $scope worked in two-way-binded. Every letter typed does an update. why not just get the values on submit?

With web, it's very common to do this, they pass the form submit and get the value based on the element's reference. for React Native however, we setup two-way binding with the component state. But WAIT, there is another way!

Using TextInput vs Input from React-native-elements, getting the value of inputs, I advise not updating state on every keypress, it feels way overkill, we should be able to just grab these values on the form submit using the _lastNativeText (https://github.com/facebook/react-native/issues/511)

Example of _lastNativeText

Everyone uses the state for this, on Web, they use the DOM, simple look at the name tag and value, but on Mobile, it’s a little different, we use the ref and createRef, much like linking the angular.element. I’m waiting for that day to come, one of the nicest things was to link an input with ng-model and it easily having the value.  But until then, I wanted to share this method, incase you're setting state values for every input you have for a form, and even then I recommend just using an object and updating that object, like so.

Your output for the form object will contain firstName


Hopefully this article helped you reduce the number of state references you make in your React Native views. Let me know what you think and what you prefer, the lastNativeText or using an object with onChangeText. Thanks, and until next time.

Eric Cavazos

Eric Cavazos

https://codelabs.io

I love to build software, workout, and snowboard...

View Comments