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
JavaScript
x
29
29
1
import React from 'react';
2
import { connect } from 'react-redux';
3
4
class MarkDownBox extends React.Component{
5
render(){
6
return(
7
<div className="markedContainer">
8
<div className="markedHeader" ><h1>Raw Mark Down</h1></div>
9
<textarea name="markdownarea" id="markdownarea" value={this.props.message} onChange={this.props.onChangeText}></textarea>
10
</div>
11
)
12
}
13
}
14
15
const mapStateToProps = (state) => {
16
return{
17
message: state.text
18
}
19
}
20
21
const mapDispatchToProps = (dispatch) => {
22
return{
23
onChangeText: (event) => dispatch({type: 'onChangeText',event} )
24
25
}
26
}
27
28
export default connect(mapStateToProps,mapDispatchToProps)(MarkDownBox);
29
This is my reducer
JavaScript
1
19
19
1
const initialState = {
2
text: 'Sample text'
3
}
4
5
6
const reducer = (state = initialState, action) => {
7
const newState = {state}
8
switch(action.type){
9
case 'OnChangeText':
10
newState.text = action.event.target.value;
11
return newState
12
default:
13
return state
14
}
15
}
16
17
18
export default reducer;
19
MapStateToProps works fine as it sets the value of the text field. The text field, however, does not record any changes.
Advertisement
Answer
In the reducer your case OnChangeText
start with uppercase and dispatch({type: 'onChangeText',event})
with lowercase, so ideally to be like:
JavaScript
1
7
1
const mapDispatchToProps = (dispatch) => {
2
return{
3
onChangeText: (event) => dispatch({type: 'ON_CHANGE_TEXT',payload: event.target.value} )
4
5
}
6
}
7
And in the reducer:
JavaScript
1
6
1
case 'ON_CHANGE_TEXT':
2
return {
3
state,
4
text: action.payload
5
}
6