Yahya Gok
3 min readMar 25, 2021

--

How does MapDispatchToProps work in React-Redux ?

In this article, I’d like to talk about map dispatch to props function in react-redux and I will go over this with my existing project.

let’s say that I have an action.js file. This file does post request. After it does post request. We need to connect this to I need to connect to a component that I want to connect. Here is the action.js called addComment.js.

addComment action.js file

on below picture. I wanted to connect this above action to this below component. To do this, on line 3( on the below picture) we have to import that action with this curly brackets.

import { addComment} from ‘../actions/addComment’

this is Commentinput component that we connect above action to this.

After we complete this step, we are ready to use this addComment action to do the job. The job is add one more comment to our existing comment database. meaning adding the new comment to our state and page so to do this, we do mapDispatchToProps function.

Here above picture, it shows how can we declare a map dispatch to props function. After return, inside the curly brackets you don’t have to use same name as addComment, it could be anything you like,

addComment: (data) => dispatch(addComment(data)), however, after inside the dispatch addComment should be match with action that we want to use. Data as an argument is coming form action.js. If you look at the first picture of this article, you will see the data as an argument of addComment. This data also could be a different name. It doesn’t have to be same as action’s attribute name. So in action, addComment function has one argument, here in the dispatch also should be one argument. there is also another way to declare this mapDispatchToProps function.

below picture shows how can we declare in another way. on line 43(below picture) , we have {addComment} directly symbolize mapDispatchToProps. Without typing const mapDispatchToProps = dispatch => {

}

we could add our action.js file which is addComment function. Also, we have to import the action.js, otherwise it won’t work.

import { addComment} from ‘../actions/addComment’

and the last step is using this mdp which is short way of typing mapStateToProps.

As you can see below picture(picture number 5), we added this.props.addComment(data)

‘this’ is coming from class function component. If this would be function component, we would have to type; props.addComment(data).

Additionally, props is coming from mdp, when we want to use mdp or msp we have to use props.

number 5

References

--

--