Search code examples
javascriptreactjsreduxreact-redux

How do you dispatch an action along with a DOM event?


I'm picking up working with react and redux, while handling state locally I am able to pass events along with onChange handlers so as to access the value with event.target.value and set them to state. Unfortunately, I am unable to pass the event to MapDispatchToProps

I have tried passing the event along with the prop assigned to the onChange handler

This is my component

import React from 'react';
import { connect } from 'react-redux';

class MarkDownBox extends React.Component{
    render(){
        return(
            <div className="markedContainer">
                <div className="markedHeader" ><h1>Raw Mark Down</h1></div>
                <textarea name="markdownarea" id="markdownarea" value={this.props.message} onChange={this.props.onChangeText}></textarea>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return{
      message: state.text
    }
  }
  
  const mapDispatchToProps = (dispatch) => {
    return{
      onChangeText: (event) => dispatch({type: 'onChangeText',event} )
    
    }
  }
  
  export default connect(mapStateToProps,mapDispatchToProps)(MarkDownBox);

This is my reducer

const initialState = {
    text: 'Sample text'
}


const reducer = (state = initialState, action) => {
    const newState = {...state}
    switch(action.type){
        case 'OnChangeText':
            newState.text = action.event.target.value;
            return newState    
         default: 
         return state
    }
}


export default reducer;

MapStateToProps works fine as it sets the value of the text field. The text field, however, does not record any changes.


Solution

  • In the reducer your case OnChangeText start with uppercase and dispatch({type: 'onChangeText',event}) with lowercase, so ideally to be like:

    const mapDispatchToProps = (dispatch) => {
     return{
       onChangeText: (event) => dispatch({type: 'ON_CHANGE_TEXT',payload: event.target.value} )
    
     }
    } 
    

    And in the reducer:

     case 'ON_CHANGE_TEXT':
            return {
               ...state,
               text: action.payload
             }