EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Software Development Basics React Redux Connect
Secondary Sidebar
React Native Tutorial
  • Basic
    • What is React Native?
    • React Versions
    • React Constructor
    • React Native Architecture
    • React Native Libraries
    • React Components Libraries
    • React Native Components
    • React Component Library
    • React Component Lifecycle
    • React Native Framework
    • React Higher Order Component
    • React Ternary Operator
    • React Native Charts
    • React Native Layout
    • React Native Grid
    • React Native Fetch
    • React Native Modal
    • React Native SVG
    • Button in React Native
    • React List Components
    • React Native Element
    • React Native FlatList
    • React Native SectionList
    • react native dropdown
    • React Native Menu
    • React Native State
    • React State Management
    • React Native Tabs
    • React Native Tab Bar
    • React Format
    • React-Native Switch
    • React Native Firebase
    • React Native Flexbox
    • React Native StatusBar
    • React Native ScrollView
    • React Native Horizontal Scroll
    • React Native ListView
    • React Native TextInput
    • React Native Table
    • React-Native Border Style
    • React Native Search Bar
    • React-Native StyleSheet
    • React Native Vector Icons
    • React Native Login Screen
    • React Native Splash Screen
    • React Native Image Picker
    • React Native Navigation
    • React Native Swift
    • React Controlled Input
    • React Fragment
    • React Native Color
    • React native useeffect
    • React Portals
    • React Map
    • React Refs
    • React shouldComponentUpdate()
    • React ComponentDidMount()
    • React componentWillUpdate()
    • React componentWillMount()
    • React Native Orientation
    • React Native Box Shadow
    • React Native SafeAreaView
    • React Native Background Image
    • React Native Animation
    • React Native Form
    • React Props
    • React PropTypes
    • React Native Linear Gradient
    • React Native AsyncStorage
    • React Error Boundaries
    • React Native Progress Bar
    • React-Native Calendar
    • React Native Linking
    • React Native DatePicker
    • React Native Image
    • React Native Drawer
    • React Native Drawer Navigation
    • React Native Fonts
    • Styling in React Native
    • React Native Overlay
    • React Native OneSignal
    • React Native Template
    • React Native Router
    • React Router Transition
    • React Dispatcher
    • React Native Transform
    • React Native zIndex
    • React Native Redux
    • React JSX
    • React native keyboardavoidingview
    • React Native Permissions
    • React Redux Connect
    • React Native Material
    • React Native Gesture Handler
    • React Native Theme
    • React Native Picker
    • React Native Slider
    • React native websocket
    • React native opacity
    • React native usestate
    • React Native Keep Awake
    • React Native Accessibility
    • React Native Justify Content
    • MobX React Native
    • React Native Authentication
    • React Native UUID
    • React Native Geolocation
    • React Native Debugger
    • React Native Carousel
    • React Native Local Storage
    • React Native TypeScript
    • React Bootstrap
    • ReactDOMServer
    • React Native SQLite
    • React Native Interview Questions
    • React Native ActivityIndicator
    • Global Variable React Native

React Redux Connect

By Rahul DubeyRahul Dubey

React Redux Connect

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?

Redux connects works for a react based application

The above diagram shows us how the does it works for a react based application.

Let us see with the help of some examples.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,697 ratings)

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:

React Redux Connect

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 –

  1. React Constructor
  2. React Native Charts
  3. React-Native Border Style
  4. React Native Animation
Popular Course in this category
React JS Redux Training (1 Course, 5 Projects)
  1 Online Courses |  5 Hands-on Projects |  18+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Software Testing Training (11 Courses, 2 Projects)4.9
Selenium Automation Testing Training (11 Courses, 4+ Projects, 4 Quizzes)4.8
Appium Training (2 Courses)4.7
JMeter Testing Training (3 Courses)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more