Using the connect () function from the react-redux package

In the article, the translation of which we publish today, we will talk about how to create container components in React-applications that are associated with the state of Redux. This material is based on the description of the mechanism of state management in React using the package react-redux . It is assumed that you already have a basic understanding of the architecture and API libraries, of which we will talk. If this is not the case, refer to the documentation on React and Redux .
 
 
Using the connect () function from the react-redux package
 
Flux , Redux , MobX .
 
 
Redux is a library designed to create containers used to store application state. It offers the developer clear tools for managing the state, which behave predictably. This library is suitable both for applications written in pure jаvascript, and for projects that were developed using any framework. Redux is small in size, but it allows you to write reliable applications that work in different environments.
 
 
Here's how to create the repository Redux:
 
 
import {createStore} from 'redux';
const initialState = {
auth: {loggedIn: false}
}
const store = createStore ((state = initialState, action) => {
.
.switch (action.type) {
.
case "LOG_IN":
return {state, auth: {loggedIn: true}};
Break;
Break;
.
Case "LOG_OUT":
Return {state, auth: {loggedIn: false}};
Break;
.
Default:
Return state;
}
})

 

The package react-redux


 
The react-redux package provides React bindings for the Redux state container, making it extremely easy to connect the React application to the Redux repository. This allows you to separate the components of a React-based application, based on their relationship to the repository. Namely, we are talking about the following types of components:
 
 
  1.  
  2. Presentation components. They are responsible only for the appearance of the application and are not aware of the status of Redux. They receive data through properties and can callbacks, which are also passed to them through properties.  
  3. Components-containers. They are responsible for the operation of the internal mechanisms of the application and interact with the state of Redux. They are often created using react-redux, they can implement the redux actions. In addition, they subscribe to state changes.  

 
Details on such an approach to the separation of responsibility of components can be read here . In this material, we will mainly talk about the container components connected to the Redux state using react-redux.
 
 
The react-redux package has a very simple interface. In particular, the most interesting in this interface is the following:
 
 
  1.  
  2. - allows you to create a wrapper for the React-application and make the Redux state accessible to all container components in its hierarchy.  
  3. connect ([mapStateToProps],[mapDispatchToProps],[mergeProps],[options]) - allows you to create higher-order components. This is necessary to create container components based on React's basic components.  

 
Install react-redux for the purpose of using this package in the project as follows:
 
 
    npm install react-redux --save    

 
Based on the assumption that you have already configured the Redux repository for your React application, here's an example of connecting the application to the Redux repository:
 
 
    import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import createStore from './createReduxStore';
const store = createStore ();
const rootElement = document.getElementById ('root');
ReactDOM.render ((

Here is page of the documentation, having familiarized with which, you can learn about what parameters can be used with connect () , and how they modify the behavior of this function.
 
 


 


 
Before converting a regular React component to a container component using connect () , you need to create a Redux store, to which this component will be connected.
 
 
Suppose we have a container component NewComment , which is used to add new comments to the publication, and, in addition, displays a button for sending a comment. The code that describes this component can look like this:
 
 
    import React from 'react';
import {connect} from 'react-redux';
class NewComment extends React.Component {
input = null
writeComment = evt => {
evt.preventDefault ();
const comment = this.input.value;
comment && this.props.dispatch ({type: 'WRITE_COMMENT', comment});
}
render () {
const {id, content} = this.props.comment;
return ?
?
. this.input = e} placeholder = "Write a comment" />
. Submit Comment .
.
.
)
}
}
export default connect () (NewComment);
 
In order for this component to be used in the application, it will be necessary to describe the Redux store to which this component needs to be connected. Otherwise, an error occurs. There are two ways to do this, which we will now consider.
 
 

Setting the store property in the container component


 
The first way to equip a component with a Redux repository is to pass a reference to such a store as a property value of store component:
 
 
    import React from 'react';
import store from './reduxStore';
import NewComment from './components/NewComment';
function CommentsApp (props) {
return
}

 

Setting the store property in the component.


 
If you want to set the Redux repository for the application only once, then you will be interested in the way that we will now consider. It is usually suitable for applications that use only one Redux store.
 
 
The react-redux package provides the developer with component , which can be used to wrap the root component of the application. It takes the property store . It is assumed that it is a link to the Redux repository that you plan to use in the application. Property store is transferred, according to the application hierarchy, to the container components, using the React context mechanism:
 
 
    import React from 'react';
import ReactDOM from 'react-dom';
import store from './reduxStore';
import {Provider} from 'react-redux';
import NewComment from './components/NewComment';
function CommentsApp (props) {
return
}
ReactDOM.render (

), Document.getElementById ('root'))

 

▍Organization of access to ownProps


 
As already mentioned, the functions mapStateToProps and mapDispatchToProps , transmitted by connect () , can be declared with the second parameter ownProps , which is the properties of the component.
 
However, there is one problem here. If the number of mandatory parameters of the declared function is less than ? then ownProps will not be transmitted. But if the function is declared with no mandatory parameters or, at least, with 2 parameters, ownProps will be transmitted.
 
 
Let's consider some variants of work with ownProps .
 
 

Declare a function without parameters


 
    const mapStateToProps = function () {
console.log (arguments[0]); //state
console.log (arguments[1]); //ownProps
};};

 
In this situation, ownProps is passed, since the function is declared without the required parameters. As a result, the following code will also work, written using the new syntax of the remaining ES6 parameters:
 
 
    const mapStateToProps = function ( args) {
console.log (args[0]); //state
console.log (args[1]); //ownProps
};};

 

Declare a function with one parameter


 
Consider the following example:
 
 
    const mapStateToProps = function (state) {
console.log (state); //state
console.log (arguments[1]); //undefined
};};

 
There is only one parameter, state . As a result, arguments[1] takes the value undefined because of the fact that ownProps not getting through.
 
 

Declare a function with the default parameter


 
    const mapStateToProps = function (state, ownProps = {} {
console.log (state); //state
console.log (ownProps); //{}
};};

 
There is only one required parameter, state , since the second parameter, ownProps , is optional because it is set to the default value. As a result, since there is only one mandatory parameter, ownProps is not passed, and mapping is performed with the default value that was assigned to it, that is, with an empty object.
 
 

Declare a function with two parameters


 
    const mapStateToProps = function (state, ownProps) {
console.log (state); //state
console.log (ownProps); //ownProps
};};

 
Here everything is arranged very simply. Namely, in this situation, the transmission of is made. ownProps because the function is declared with two required parameters.
 
 

Results of


 
Having mastered this material, you learned about when and how to use API connect () , provided by the package react-redux and designed to create container components that are connected to the Redux state. Here we described in some detail the device of the function connect () and about working with it, however, if you want to learn more about this mechanism, in particular - to familiarize yourself with the options for using it - take a look at
this
the documentation section for react-redux.
 
 
Dear readers! Do you use the package react-redux in your projects?
 
 
+ 0 -

Add comment