mapDispatchToProps in react-redux
In this chapter, we will understand mapDispatchToProps in react-redux and how can we use the same. As we learned in the previous chapters, we use the connect method for connecting the redux store to react.
While connecting we pass tow objects first one is mapStateToProps and second one is mapDispatchToProps. The mapDispatchToProps is an object which lists the properties with dispatch details assigned, like what type of action and payload. Let’s see an example of the same.
import React from 'react'; import { connect } from 'react-redux'; const LogOutForm = (props) => { return ( <div className='form'> <h1>Welcome to react tutorial</h1> <button onClick={props.onLogout}>Logout</button> </div> ) } const mapStateToProps = state => { return { isEmployeeLoggedIn: state.login.isEmployeeLoggedIn } } const mapDispatchToProps = dispatch => { return { onLogout: () => dispatch({ type: 'LOGOUT' }) } } export default connect(mapStateToProps, mapDispatchToProps)(LogOutForm);
As we can see in the above code snippet, we have registered the logout action with the props.onLogout on the button logout.