Open In App

How to connect the components using Connect() in React Redux

Last Updated : 04 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In React Redux, you use the connect() function to connect your components to the Redux store. This function takes two parameters: mapStateToProps and mapDispatchToProps. mapStateToProps maps the store's state to the component's props, while mapDispatchToProps maps dispatch actions to props. By using connect( ), your components can access the store's state and dispatch actions easily.

Output Preview: Let us have a look at how the final output will look like.

cdw

Prerequisites

Approach

  • Initialize a new React project (Counter) using Create React App. Install necessary dependencies such as redux, react-redux, and any additional packages required for your project.
  • Create a directory structure for Redux-related files, define your actions , reducers, creating store etc.
  • Design the component hierarchy based on your application's requirements. Create React components for UI elements, organizing them into appropriate folders (e.g., src/components). Ensure each component is designed to be reusable and focused on a single responsibility.
  • Connecting Components to Redux: This is the most crucial part of state management. Here importing react-components, Defining mapStateToProps function, mapDispatchToProps function such work is done. Use connect() to connect components to the Redux store, passing in mapStateToProps and mapDispatchToProps as arguments is also done here.

Steps to create application

Step 1: Create a reactJS application by using this command

npx create-react-app my-app

Step 2: Navigate to project directory

cd my-app

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install react react-dom redux react-redux

Project Structure:

1711282615926
Counter Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"redux": "^4.1.2",
"react-redux": "^7.2.6"
}

Example: Implementation to showcase how to connect the components using connect method in react redux.

CSS
/* style.css */

body {
    margin: 0;
    display: grid;
    place-items: center;
    height: 100vh;
}

img {
    margin-left: 80px;
}


button {
    border-radius: 8px;
    border: 1px solid transparent;
    padding: 0.6em 1.2em;
    font-size: 1em;
    font-weight: 500;
    font-family: inherit;
    cursor: pointer;
    margin: 10px;
    transition: border-color 0.25s;
}

p {
    text-align: center;
}

button:hover {
    border-color: #646cff;
}
JavaScript JavaScript JavaScript

Output:
cdw


Next Article

Similar Reads

three90RightbarBannerImg