Updated April 6, 2023
Introduction to React-Redux Connect
Redux is one of the best State Management tools whenever the task is to build an application for scaling. Initially, it is quite complex to work upon, but Redux comes as a savior for the developers with a good codebase. The major challenge using Redux is to connect the components to the Redux Store and actions. Mostly, everyone keeps all the Redux bindings at a single place; sooner, this becomes more typical with the complex component hierarchies.
How React Redux Connect done with Examples?
The above diagram shows us how the does it works for a react based application.
Let us see with the help of some examples.
1. Components inside src folder-
- ComponentListTodo folder
- App.css
- App.js
- App.test.js
- ComponentPageView.js
- WorkerService.js
- action.js
- index.css
- index.js
- reducingreducers.js
- storingstore.js
2. Components inside ComponentListTodo folder-
a) ComponentButton.js
import React, { Component } from 'react';
import { connect } from 'react-redux'
class ComponentButton extends Component {
render() {
const { itemId, deleteItem, printItem } = this.props;
return (
<div className="list-item-button">
<button onClick={() => printItem(itemId)} className="btn btn-print">Print Task</button>
<button onClick={() => deleteItem(itemId)} className="btn btn-del">Delete Task</button>
</div>
)
}
}
export default ComponentButton;
b) ComponentCheck.js
import React from 'react';
export default function ComponentCheck({itemId, itemText, isChecked, toggleItem}){
return (
<div className="list-item-text">
<input
type="checkbox"
onChange={() => toggleItem(itemId)} checked={isChecked}
/>
<span>{itemText}</span>
</div>
)}
c) ComponentItemToDo.js
import React, { Component } from 'react';
import { connect } from 'react-redux'
import ComponentText from "./ComponentText";
import ComponentCheck from './ComponentCheck';
import { deleteItem, printItem, togglCheck } from '../action';
import ComponentButton from './ComponentButton';
class ComponentItemTodo extends Component{
render(){
const { itemId, item, togglCheck, deleteItem, printItem } = this.props;
return (
<div className="list-item">
{ item.isCheckItem ? (
<ComponentCheck itemId={itemId} itemText={item.label} isChecked={item.isChecked} toggleItem={togglCheck}
/>
) : (
<ComponentText itemId={itemId} itemText={item.label}
/>
)}
{
item.hasActions && (
<ComponentButton itemId={itemId} printItem={printItem} deleteItem={deleteItem}
/>
)
}
</div>
)
}
}
const DispatchmapToProps = { deleteItem, printItem, togglCheck };
export default connect(null, DispatchmapToProps)(ComponentItemTodo);
d) ComponentText.js
import React from 'react';
export default function ComponentText({ itemId, itemText }){ return (
<div className="list-item-text">
<span>{itemText}</span>
</div>
)}
e) index.js
import React, { Component } from 'react';
import { connect } from 'react-redux'
import ComponentItemToDo from './ComponentItemToDo';
class ComponentListTodo extends Component{ render(){
const { items } = this.props;
return (
<div className="todo-list">
<h2>ToDo List</h2>
{items.map((item, idx) => (
<ComponentItemToDo item={item} itemId={idx} key={idx}
/>
))}
</div>
)
}
}
function StatemapToProps(state) { return {
items: state.tasks
}
}
export default connect(StatemapToProps, null)(ComponentListTodo);
3. App.css
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear; height: 40vmin;
pointer-events: none;
}
.App-header {
background-color: #53cfa5;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: #8c9c96;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
4. App.js
import React from 'react';
import { Provider } from 'react-redux'
import stores from './storingstore';
import ComponentPageView from './ComponentPageView';
function Application() { return (
<Provider store={stores}>
<ComponentPageView />
</Provider>
);
}
export default Application
5. App.test.js
import React from “react”;
import ReactDOM from "react-dom";
import Application from "./App";
it("crashes without renders", () => {
const div = document.createElement("div");
ReactDOM.render(<Application />, div);
ReactDOM.unmountComponentAtNode(div);
});
6. ComponentPageView.js
import React, { Component } from "react";
import ComponentListTodo from "./ComponentListTodo";
export default class ComponentPageView extends Component {
render() {
return <ComponentListTodo />;
}
}
7. Workerservice.js
const isLocalhost = Boolean( window.location.hostname === "localhost" ||
window.location.hostname === "[::1]" ||
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === "production" && "Workerservice" in navigator) {
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
return;
}
window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/worker-service.js`;
if (isLocalhost) {
checkValidServiceWorker(swUrl, config);
navigator.serviceWorker.ready.then(() => { console.log("."
);
});
} else {
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
console.log( "." );
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
console.log("Cache Content for offline use.");
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error("Error while service worker registration:", error);
});
}
function checkValidServiceWorker(swUrl, config) {
fetch(swUrl)
.then(response => {
const contentType = response.headers.get("content-type");
if (
response.status === 404 ||
(contentType != null && contentType.indexOf("javascript") === -1)
) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log("Application in Offline Mode because No internet connection discovered.");
});
}
export function unregister() {
if ("Workerservice" in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
8. action.js
export const DELETE_ITEM = "DELETE_ITEM";
export const PRINT_ITEM = "PRINT_ITEM";
export const TOGGLE_CHECK = "TOGGLE_CHECK";
export function deleteItem(itemIndex) {
return {
type: DELETE_ITEM,
itemIndex
};
}
export function printItem(itemIndex) {
return {
type: PRINT_ITEM, itemIndex
};
}
export function togglCheck(itemIndex) {
return {
type: TOGGLE_CHECK,
itemIndex
};
}
9. index.css
body {
margin: 0;
font-family: BlinkMacSystemFont,-apple-system, "Helvetica Neue", "Droid Sans", "Fira Sans", "Cantarell","Ubuntu", "Oxygen", "Roboto", "Segoe UI",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: "Courier New", Consolas, Monaco, Menlo, source-code-pro, monospace;
}
.todo-list{
width: 501px;
margin-left: auto;
margin-right: auto;
margin-top: 41px;
background-color: #ffa8c5;
}
.list-item{
border: 1px solid #3c403e;
padding: 6px;
margin-top: 11px;
}
.list-item .list-item-text{
display: inline-block;
margin-left: 11px;
background-color: #bbf582;
}
.list-item .list-item-text{
display: inline-block;
margin-left: 11px;
}
.list-item .list-item-button{
display: inline-block;
margin-left: 11px;
}
.list-item .list-item-button button{
margin-left: 11px;
background-color: #7eb7ed;
}
10. index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import Application from "./App";
import * as Workerservice from "./Workerservice";
ReactDOM.render(<Application />, document.getElementById("root"));
Workerservice.unregister()
11. reducingreducers.js
import { DELETE_ITEM, PRINT_ITEM, TOGGLE_CHECK } from './action';
const initialState = {
tasks: [
{
label: "Drink 2 Liters of Water",
isCheckItem: true,
hasActions: true,
isChecked: true
},
{
label: "Walk at 4 P.M.",
isCheckItem: false,
hasActions: true,
isChecked: false
},
{
label: "Clean Room",
isCheckItem: true,
hasActions: false,
isChecked: true
},
{
label: "Call at 9 P.M. Tonight",
isCheckItem: false,
hasActions: false,
isChecked: false
}
]
}
export default function todoReducer(state, action) {
if (typeof state === 'undefined') {
return initialState
}
switch(action.type){
case DELETE_ITEM:
console.log("deleting");
break;
case PRINT_ITEM:
console.log("printing");
break;
case TOGGLE_CHECK:
state = {
...state,
tasks: state.tasks.map(
(task, i) => i === action.itemIndex ?
{...task, isChecked: !task.isChecked}
: task
)
}
}
return state
}
12. storingstore.js
import { createStore } from "redux";
import todoReducer from "./reducingreducers";
export default createStore(todoReducer)
Output:
Conclusion
On the basis of the above discussion, we are clear on the part of making React Redux Connect in an Application. We successfully created a To-Do-List React application with Redux Connect.
Recommended Articles
This is a guide to React Redux Connect. Here we discuss the introduction and working of React Redux Connect along with examples and code implementation. You may also look at the following articles to learn more –