4

I'm creating form in React Native and Redux. I added TextInput and want to change the state of this field in Reducer. I have a trouble, because I don't know how to add (change) => this.setState({change}) function to my Redux architecture. I use combine reducers and have no idea how to bind that value. Saying in short, I need to gain default behaviour of the TextInput on change function but I have to use Redux to do it.

Form.js

const mapDispatchToProps = dispatch => {
  return {
      changeNameInput: () => dispatch({type: 'CHANGE_NAME_INPUT'})
  };
};

const mapStateToProps = state => {
  return {
      change: state.changeNameInput.change
  };
};

class Form extends React.Component {
  render() {
    return (
      <View>
         <FormLabel>Name</FormLabel>
         <TextInput
            onChangeText={this.props.changeNameInput}
            value={this.props.change}
        />
      </View>
    );
  }
}

Reducer.js

const initialState = {
    change: 'Your name'
   };

   const changeinputReducer = (state = initialState, action) => {
     switch (action.type) { 
       case 'CHANGE_NAME_INPUT':

  //Problem

         return {...state, change: '????' };
        default:
         return state;
     }
   };

   export default changeinputReducer;

1 Answer 1

7

For passing value from TextInput to reducer, you need to change in dispatch function:

const mapDispatchToProps = dispatch => {
  return {
      changeNameInput: (text) => dispatch({type: 'CHANGE_NAME_INPUT', text})
  };
};

and in your reducer change it to

const changeinputReducer = (state = initialState, action) => {
     switch (action.type) { 
       case 'CHANGE_NAME_INPUT':

  //Solution

         return {...state, change: action.text };
        default:
         return state;
     }
   };

Hope it worked..

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome.What makes different if i use onChangeText={this.props.changeNameInput.bind(this)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.