Reputation: 4783
I am currently learning how to use Redux after using vanilla React Native for some time. I am trying to understand how to store a TextInput
's value. Previously I would have simply stored the value in state. I have tried a few things including the code sample below.
Currently, todoInput.value
is undefined. I have also tried directly assigning the value
prop of the TextInput
to a variable defined with let
but this also stays undefined.
How can I alter the code so that the value of the TextInput
is not undefined?
import React from 'react';
import { View, Button, TextInput } from 'react-native';
import { connect } from 'react-redux';
import { addTodo } from '../actions';
const addNewTodo = (dispatch, value) => {
dispatch(addTodo(value));
}
const AddTodo = ({ dispatch }) => {
let todoInput;
return (
<View>
<TextInput ref={inputRef => todoInput = inputRef} />
<Button title="Add Todo" onPress={() => addNewTodo(dispatch, todoInput.value)}></Button>
</View>
);
};
export default connect()(AddTodo);
Upvotes: 2
Views: 3424
Reputation: 22189
You can make a stateful component in order to pass the value
to the component state
so that it can be used in multiple places.
Based on your scenario (Assuming that the component is connected)
class AddTodo extends React.Component {
state = {
todoInput: null
}
addNewTodo = () => {
this.props.dispatch(addNewTodo(this.state.todoInput))
}
render() {
return (
<View>
<TextInput onChangeText={text => this.setState({todoInput: text})} value={this.state.todoInput} {...{/*Other Props*/}}/>
<Button title="Add Todo" onPress={this.addNewTodo}></Button>
</View>
)
}
}
Upvotes: 6