Category: React

Optical Character Recognition in React

Hello People. This article discusses about Optical Character Recognition in React. OCR is very useful when you want to extract text from a scanned document on a browser. Applying OCR technology through a React application, you can upload your images in various formats and can apply OCR to extract text content so easily. 

How to achieve Optical Character Recognition in React?

We’ll use two third party libraries for different purposes. The first one is “tesseract.js”. It’ll allow us to run OCR easily with just a couple of lines of code. The second one is “react-images-upload”, it’ll allow us to upload images to the browser and access their locations easily.

Here we do a couple of new things and you may want to follow them carefully. We should put the code snippet above the return we need to create 3 states here to achieve different goals. The first state we have here is to take the image URLs from our ImageUploader component and save it for further processing, the second state is the one that we keep our OCR applied texts, and the third one is the one for loading logic.

Optical Character Recognition in React

onDrop function is called whenever a change happened in our ImageUploader component . So whenever a change happens like adding or removing the photos in our component this function will be fired up. It’ll take the argument we need in the second position after the onChange event is fired so we can simply bypass the first argument by putting “_” and take the second one. It has link/links for our images in it and it’ll bring the full latest list of links so whenever we get a list from our function we can safely put that in our array.

runOcr function seems tricky but in fact, it’s quite simple, we take our URLs state and run the following recognition script for each element. Tesseract recognize function takes at least 2 arguments, first is the URL and the second one is the target language, tesseract.js supports over 100 languages. After the requests resolve we take output text and add it to our current array. After we fire runOcr command we can setIsLoading to true so we can display our spinner.

Hope this article on Optical Character Recognition in React is useful to you. Please read What is Node Red and its application

Production stage issue in APP development

Hello People. This article discusses about a production stage issue in APP development. If you are a react native expo app developer, and you use local data for maps, you might have noticed that the map screen breaks in production. This is because you have not installed react-native-maps.

In this article, let us see how to use react-native-maps in a expo project.

Installation in expo

expo install react-native-maps

Let us see an example code of a map screen.

MapScreen.JS

import * as React from 'react';
import MapView from 'react-native-maps';
import { StyleSheet, Text, View, Dimensions } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <MapView style={styles.map} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  map: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
});

Configuration

An additional configuration is not necessary to use react-native-maps in Expo Go. But if you want to deploy your standalone app you should follow instructions below.

Production stage issue in APP development

Deploying Google Maps to Android standalone app

1. Register a Google Cloud API project and enable the Maps SDK for Android

  • Open your browser to the Google API Manager and create a project.
  • After that, go to the project and enable the Maps SDK for Android

2. Get your app’s SHA-1 certificate fingerprint ready

  • If you are deploying your app to the Google Play Store, you will need to have created a standalone app and uploaded it to Google Play at least once in order to have Google generate your app signing credentials.
    • Go to the Google Play Console → (your app) → Setup → App Integrity
    • Copy the value of SHA-1 certificate fingerprint
  • If you are sideloading your APK or deploying it to another store, you will need to have created a standalone app, then run expo fetch:android:hashes and copy the Google Certificate Fingerprint.

3. Create an API key

  • Go to Google Cloud Credential manager and click Create Credentials, then API Key.
  • In the modal, click Restrict Key.
  • Under Key restrictions → Application restrictions, ensure that the Android apps radio button is chosen.
  • Click the + Add package name and fingerprint button.
  • Add your Android package name from app.json to the package name field.
  • Add or replace the SHA-1 certificate fingerprint with the value from step 2.
  • Click Done and then click Save

4. Add the API key to your project

  • Copy your API Key into your app.json under the android.config.googleMaps.apiKey field.
  • Rebuild the app binary and re-submit to Google Play or sideload it (depending on how you configured your API key) to test that the configuration was successful.

Hope this article on Production stage issue in APP development is useful to you. Please read How to make a website responsive using HTML

How to make a website responsive using HTML

Hello People. This article discusses about how to make a website responsive using HTML. Responsive web designing is creating web pages that fit on all devices. It is about using HTML and CSS to automatically resize, hide, shrink, or enlarge a website to make it look good on all devices (desktops, tablets, and phones). A responsive web design will automatically adjust for different screen sizes and viewports.

Setting The Viewport

To create a responsive website, add the following <meta> tag to all your web pages:

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

This will set the viewport of your page. This line will give the browser instructions on how to control the page’s dimensions and scaling.

Responsive Images

Responsive images are images that scale automatically to fit any browser size.

Use the width Property

If the CSS width property is set to 100%, the image will be responsive and it can scale up and down. Add the following line.

<img src=”img_girl.jpg” style=”width:100%;”>

Use the max-width Property

If the max-width property is set to 100%, the image can scale down. But never scale up to be larger than its original size. The solution is to use the max-width property. Use the following line.

<img src=”img_girl.jpg” style=”max-width:100%;height:auto;”>

Display Different Images Depending on Browser Width

Using the HTML <picture> element, you can define different images for different browser window sizes. Example is given below.

<picture>
  <source srcset=”img_smalltiger.jpg” media=”(max-width: 600px)”>
  <source srcset=”img_tigers.jpg” media=”(max-width: 1500px)”>
  <source srcset=”tigers.jpg”>
  <img src=”img_smalltiger.jpg” alt=”Tigers”>
</picture>

Responsive Text Size

The text size can be set with a “vw” unit, which means the “viewport width”. By doing this, the text size will follow the size of the browser window. Use the following line.

<h1 style=”font-size:10vw“>Hello World</h1>

How to make a website responsive using HTML

Media Queries

It is also common to use media queries in responsive web pages. Using media queries you can define completely different styles for different browser sizes. Example is given below.

<style>
.left, .right {
  float: left;
  width: 20%; /* The width is 20%, by default */
}

.main {
  float: left;
  width: 60%; /* The width is 60%, by default */
}

/* Use a media query to add a breakpoint at 800px: */
@media screen and (max-width: 800px) {
  .left, .main, .right {
    width: 100%; /* The width is 100%, when the viewport is 800px or smaller */
  }
}
</style>

Responsive Web Design – Frameworks

There are many popular CSS Frameworks that offer responsive design. They are free, and easy to use.

Hope this article on how to make a website responsive using HTML is useful to you. Please read MVVM pattern in KnockoutJS

How to use EmailJS in React website

Hello People. This article discusses how to use EmailJS in React website. In almost all the web applications we create, we need to send emails to users, whether it be a support email or verification one. We will be using react-bootstrap to build the Contact Form in react. Add ‘emailJs’ dependency using yarn or npm.

How does EmailJS work?

EmailJS helps to send emails using client-side technologies only. No server is required – just connect EmailJS to one of the supported email services, create an email template, and use our Javascript library to trigger an email.

Email templates can optionally contain dynamic variables in almost any field (e.g. subject, content, TO address, FROM name, etc) which are populated from the Javascript call. For example, the subject can be “{{ name }}, you have a new message”, and using JavaScript the name can be set to “James Dean”, for instance.

Additionally, you can easily add attachments, require CAPTCHA validation, switch between the email services without making code changes, review the history of the email request, and more.

Connecting email services

EmailJS is not sending the emails directly. Instead, it allows users to connect their email services, through which the emails will be sent. We support a long list of email services, both personal services and transactional email services.

Personal email services allow connecting personal email providers that offer basic email functionality – an email address and an inbox. These include providers like Gmail, Fastmail, Outlook 365, etc’. Personal email services are useful in EmailJS when you need to send a small number of emails to yourself, or need to send emails to other people from your personal email account. Note, your personal email account could be blocked if you go over the daily limit of the email provider, and your email address could be flagged as spam if you send unsolicited emails to multiple recipients. Our general recommendation is to use personal email services only for development purposes or for very low volume usage.

Transactional email services allow connecting dedicated transactional email providers that were designed to send out a large number of emails to a large number of recipients. These providers are usually more robust, can handle higher volumes, and provide a better email reputation (which means fewer chances your emails will end up in the spam folder). We strongly recommend you use one of these providers for your production environment.

To connect an email service:

  1. Open Email Services page in EmailJS dashboard
  2. Choose from the list of supported services and click on the service
  3. Fill out the service details
  4. Test the email service and make sure you receive the test email
How to use EmailJS in React website

Let us see the code of the contact form.

Contact.JS

import React, { useRef } from "react";
import Container from "./Container";
import Row from "./Row";
import Col from "./Col";
import { Form, Button, FloatingLabel } from "react-bootstrap";
import emailjs from "emailjs-com";
import Swal from "sweetalert2";
import "@sweetalert2/theme-dark/dark.css";


const Contact = () => {
  const form = useRef();
  const [verified, setVerified] = React.useState(false);
  const onVerify = (e) => {
    setVerified(true);
  };

  const sendEmail = (e) => {
    e.preventDefault();

    emailjs
      .sendForm(
        "servicexxxx",
        "templatexxxx",
        form.current,
        "user_xxxxxx"
      )
      .then(
        function (response) {
          Swal.fire({
            title: "Message Sent!",
            text: "Thank you for your message! I will respond shortly.",
            icon: "success",
            confirmButtonText: "Ok",
          });
          console.log("SUCCESS!", response.status, response.text);
          e.target.reset();
        },
        function (error) {
          Swal.fire({
            title: "Whoops!",
            text: "Something went wrong.",
            icon: "error",
            confirmButtonText: "Ok",
          });
          console.log("FAILED...", error);
        }
      );
  };
  return (
    <section id="contact" className="pb-4">
      <Container className="contact-wrapper">
        <Row>
          <Col size="col-md-6 justify-content-center">
            <div className="card mt-4 pb-4">
              <h1 className="heading">Let's Connect</h1>
              <Form ref={form} onSubmit={sendEmail}>
                <Form.Group className="mb-3" controlId="formBasicName">
                  <FloatingLabel
                    controlId="floatingInput"
                    label="Name"
                    className="mb-3 w-75 mx-auto"
                  >
                    <Form.Control
                      type="text"
                      placeholder="First Last"
                      name="name"
                      autoComplete="on"
                      required
                    />
                  </FloatingLabel>
                </Form.Group>
                <Form.Group className="mb-3" controlId="formBasicEmail">
                  <FloatingLabel
                    controlId="floatingInput"
                    label="Email address"
                    className="mb-3 w-75 mx-auto"
                  >
                    <Form.Control
                      type="email"
                      placeholder="name@example.com"
                      name="email"
                      autoComplete="on"
                      required
                    />
                  </FloatingLabel>
                </Form.Group>
                <Form.Group
                  className="mb-3"
                  controlId="formComment"
                ></Form.Group>
                <FloatingLabel
                  controlId="floatingTextarea2"
                  label="Comments"
                  className="w-75 mx-auto"
                >
                  <Form.Control
                    as="textarea"
                    placeholder="Leave a comment here"
                    name="message"
                    style={{ height: "100px" }}
                    required
                  />
                </FloatingLabel>
                
                <Container className="center mt-4">
                  <div className="buttonWrapper mt-4">
                    <Button
                      variant="primary"
                      className="w-75"
                      type="submit"
                      size="lg"
                      
                    >
                      Submit
                    </Button>
                  </div>
                </Container>
              </Form>
            </div>
          </Col>
        </Row>
      </Container>
    </section>
  );
};

export default Contact;

EmailJS integration has the following steps:

  • Add an email service
  • Create an email template
  • Create an HTML form
  • Send email with form details using EmailJS SDK

Then use emailjs component to send the email. You will need to pass the configuration object in this function.

emailjs
      .sendForm(
        "service_qseq79h",
        "template_wc1fped",
        form.current,
        "user_hVmW7t1Fm5PWBqZnlB8xk"
      )
  1. The first parameter is your email service ID. You can get it from emailJS dashboard.
  2. The second parameter is the template ID. You will get this from Dashboard of emailJs once registered.
  3. The third parameter is the User ID in the emailJs dashboard.

Hope this article on How to use EmailJS in React website is useful to you. Please read Node MCU for IOT applications

Nested Arrays in Javascript

Hello People. This article discusses about Nested Arrays in Javascript. We already know about “flat” arrays; each array element contains a single value, such as a number, string, or object. JavaScript lets you create arrays inside arrays, known as nested arrays. In a nested array, the elements of one array are themselves arrays. For example:


var pets = new Array ( );
pets[0] = new Array ( "Sheba", 13, "cat" );
pets[1] = new Array ( "Jasper", 12, "dog" );
alert ( pets[0][0] + " is a " + pets[0][1] + " year old " + pets[0][2] ); // Displays "Sheba is a 13 year old cat"
alert ( pets[1][0] + " is a " + pets[1][1] + " year old " + pets[1][2] ); // Displays "Jasper is a 12 year old dog"

Here we’ve created an array of 2 elements. Each element is in turn an array containing 3 elements. To access the elements of the inner arrays, you simply use two sets of square brackets. For example, pets[1][2] accesses the 3rd element of the array inside the 2nd element of the pets array.

You can nest arrays as deeply as you like. For example, here we’ve created a top-level array called animals, into which we’ve placed the above pets array, as well as a similar dinosaurs array — that has 3 levels of nesting in total:


var pets = new Array ( );
pets[0] = new Array ( "Sheba", 13, "cat" );
pets[1] = new Array ( "Jasper", 12, "dog" );
var dinosaurs = new Array ( );
dinosaurs[0] = new Array ( "Cyril", 45, "Tyrannosaur" );
dinosaurs[1] = new Array ( "Gertrude", 72, "Brontosaur" );
var animals = new Array ( pets, dinosaurs );
alert ( animals[0][1][0] + " is a " + animals[0][1][1] + " year old " + animals[0][1][2] ); // Displays "Jasper is a 12 year old dog"

If you’re used to a language like C, you may be wondering if you can create multi-dimensional arrays in JavaScript. While JavaScript doesn’t support true multi-dimensional arrays, you can use array nesting, as described above, to achieve the same effect.

Nested Arrays in Javascript

Looping through nested arrays

Of course, once you start nesting arrays you quickly end up with lots of array elements. The easiest way to work with large arrays is to use loops. And in order to process nested arrays, you need to use nested loops.

For example, the following code loops through the animals nested array we created above, displaying each of the animals, along with their ages and types:


for ( i=0; i<animals.length; i++ )
{
  for ( j=0; j<animals[i].length; j++ )
  {
    alert ( animals[i][j][0] + " is a " + animals[i][j][1] + " year old " + animals[i][j][2] );
  }
}

You now know how to create and use nested arrays in JavaScript. You’ll find nested arrays are useful when you want to store highly structured data — such as our animals example above — and when you’re creating multidimensional data structures (commonly used in games and graphics applications).

Hope this article on Nested Arrays in Javascript is useful to you. Please visit How to Create an Apple Developer Account

Push and Pop Array Methods in JavaScript

Hello People. This article explains about Push and Pop Array Methods in JavaScript. JavaScript provides us four methods to add or remove items from the beginning or end of arrays. You can use an array as a stack using these methods.

pop(): Removes an item from the end of an array

let cats = ['Bob', 'Willy', 'Mini'];

cats.pop(); // ['Bob', 'Willy']

pop() returns the removed item.

push(): Add items to the end of an array

let cats = ['Bob'];

cats.push('Willy'); // ['Bob', 'Willy']

cats.push('Puff', 'George'); // ['Bob', 'Willy', 'Puff', 'George']

push() returns the new array length.

shift(): Removes an item from the beginning of an array

let cats = ['Bob', 'Willy', 'Mini'];

cats.shift(); // ['Willy', 'Mini']

shift() returns the removed item.

unshift(): Add items to the beginning of an array

let cats = ['Bob'];

cats.unshift('Willy'); // ['Willy', 'Bob']

cats.unshift('Puff', 'George'); // ['Puff', 'George', 'Willy', 'Bob']

unshift() returns the new array length.

What is a Stack?

A stack is a data structure that holds a list of elements. A stack works based on the Last In, First out principle meaning that the most recently added element is the first one to remove. The name stack comes from the analogy to a set of physical items e.g., DVD disc, books, stacked on top each other.

A stack has many applications. For example, the simplest one is to reverse a word. To do it, you push a word into the stack, letter by letter, and pop the letters from the stack.

The other applications of the stack are “undo” mechanism in text editors, syntax parsing, function call, and expression conversion (infix to postfix, infix to prefix, postfix to infix, and prefix to infix).

Push and Pop Array Methods in JavaScript

Reverse a string using a JavaScript stack

The following example shows you how to reverse a string using a stack.

function reverse(str) {
    let stack = [];
    // push letter into stack
    for (let i = 0; i < str.length; i++) {
        stack.push(str[i]);
    }
    // pop letter from the stack
    let reverseStr = '';
    while (stack.length > 0) {
        reverseStr += stack.pop();
    }
    return reverseStr;
}
console.log(reverse('JavaScript Stack')); //kcatS tpircSavaJCode language: JavaScript (javascript)

How the script works.

The reverse() function accepts a string argument and returns its reversed version with the following logic:

  1. First, loop through the str and push each letter into the stack array.
  2. Second, pop each letter from the stack and construct the reversed string.

Hope this article on Push and Pop Array Methods in JavaScript is useful to you. Please visit How to Create an Apple Developer Account

What are objects in Javascript?

Hello People. This article discusses about what are objects in Javascript. Objects store collections of data. We can create an object with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where key is a string (a “property name”), and value can be anything.

We can create an object using one of two syntaxes. Let us create an “user” object in two different ways.

let user = new Object(); // "object constructor" syntax
let user = {};  // "object literal" syntax

Usually, we use figure brackets {...} . That declaration is an object literal.

Object Properties

We can immediately put some properties into {...} as “key: value” pairs:

let user = {     // an object
  name: "John",  // by key "name" store value "John"
  age: 30        // by key "age" store value 30
};

A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it.

In the user object, there are two properties:

  1. The first property has the name "name" and the value "John".
  2. The second one has the name "age" and the value 30.

The resulting user object is like a cabinet with two files “name” and “age”.

We can add, remove and read files from it any time.

We can access property values using the dot notation.

// get property values of the object:
alert( user.name ); // John
alert( user.age ); // 30

The value can be of any type. Let’s add a boolean one:

user.isAdmin = true;

To remove a property, we can use delete operator:

delete user.age;

We can also use multiword property names, but we must quote them.

let user = {
  name: "John",
  age: 30,
  "likes birds": true  // multiword property name must be quoted
};
What are objects in Javascript?

Square Brackets

For multiword properties, the dot access doesn’t work:

// this would give a syntax error
user.likes birds = true

JavaScript doesn’t understand that. It thinks that we address user.likes, and then gives a syntax error when comes across unexpected birds.

The dot requires the key to be a valid variable identifier. That implies: contains no spaces, doesn’t start with a digit and doesn’t include special characters.

There’s an alternative “square bracket notation” that works with any string:

let user = {};

// set
user["likes birds"] = true;

// get
alert(user["likes birds"]); // true

// delete
delete user["likes birds"];

Now everything is fine. Please note that the string inside the brackets is properly quoted (any type of quotes will do).

Square brackets also provide a way to obtain the property name as the result of any expression – as opposed to a literal string – like from a variable as follows:

let key = "likes birds";

// same as user["likes birds"] = true;
user[key] = true;

Here, the variable key may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility.

For instance:

let user = {
  name: "John",
  age: 30
};

let key = prompt("What do you want to know about the user?", "name");

// access by variable
alert( user[key] ); // John (if enter "name")

The dot notation cannot be used in a similar way:

let user = {
  name: "John",
  age: 30
};

let key = "name";
alert( user.key ) // undefined

Hope this article on What are objects in Javascript is useful to you. Please visit How to Create an Apple Developer Account

JavaScript Primitives and Reference Values

Hello People. This article discusses about JavaScript Primitives and Reference Values. In JavaScript, a variable stores two types of values: primitive and reference.

JavaScript provides six primitive types as undefinednullbooleannumberstring, and symbol . It provides a reference type object.

The size of a primitive value is fixed, therefore, JavaScript stores the primitive value on the stack.

On the other hand, the size of a reference value is dynamic so JavaScript stores the reference value on the heap.

When you assign a value to a variable, the JavaScript engine will determine whether the value is a primitive or reference value.

If the value is a primitive value, when you access the variable, you manipulate the actual value stored in that variable.

Unlike a primitive value, when you manipulate an object, you work on the reference of that object, rather than the actual object.

JavaScript Primitives and Reference Values

To determine the type of a primitive value you use the typeof operator. For example:

let x = 10;
console.log(typeof(x)); // numberCode language: JavaScript (javascript)

And

let str = 'JS';
console.log(typeof(str)); // stringCode language: JavaScript (javascript)

To find the type of a reference value, you use the instanceof operator:

let refType = variable instanceof constructor;Code language: JavaScript (javascript)

For example, the following rgb variable is an instance of the Array object:

let rgb = ['red','green','blue'];
console.log(rgb instanceof Array); // trueCode language: JavaScript (javascript)

Copying primitive values

When you assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.

Let’s take a look at the following example.

First, declare a variable a and initialize its value to 10.

var a = 10;Code language: JavaScript (javascript)
JavaScript Primitive Value Example

Second, declare another variable b and assign it a value of the variable a. Internally, JavaScript engine copies the value stored in  a into the location of b.

var b = a;Code language: JavaScript (javascript)
JavaScript Primitive Value Copying

Third, assign the variable b new value 20.

b = 20;
JavaScript Primitive Value Assigning

Since a and b have no relationship, when you change the value stored in the b variable, the value of the variable doesn’t change.

console.log(a); // 10;
console.log(b); // 20;Code language: JavaScript (javascript)

Copying reference values

When you assign a reference value from one variable to another, the value stored in the variable is also copied into the location of the new variable.

The difference is that the values stored in both variables now are the address of the actual object stored on the heap. As a result, both variables are referencing the same object.

Consider the following example.

First, declare a variable x that holds an object whose name property is 'John'.

var x = {name: 'John'};Code language: JavaScript (javascript)
JavaScript Reference Declaration

Second, declare another variable y and assign the x variable to y. Both x and y are now referencing the same object on the heap.

var y = x;Code language: JavaScript (javascript)
JavaScript Reference Assignment

Third, modify the value stored in the name property of the object using the y variable.

y.name = 'David';Code language: JavaScript (javascript)
JavaScript Reference Modifying Property

Since both x and y are referencing the same object, you can see the change if you access the object using the x variable.

console.log(x.name); // 'David'Code language: JavaScript (javascript)
JavaScript Reference Accessing Property

Hope this article on JavaScript Primitives and Reference Values is useful to you. Please visit How to Create an Apple Developer Account

When to use map state to props and map dispatch to props in React Redux

Hello People. This article is about when to use map state to props and map dispatch to props in React Redux. React provides two major mechanisms for providing data to components namely props and state. Props are read-only and allow a parent component to pass attributes to a child component. State is local and encapsulated within the component and can change at any time in the component’s lifecycle.

When using Redux-connected components, there can be three sources of props:

  • props passed from the parent component,
  • props returned from mapStateToProps,
  • props returned from mapDispatchToProps

We can connect the store to our app so we can store our app’s state in the store by using React-Redux’s connect function.

connect takes 2 functions, which are mapStateToProps and mapDispatchToProps . They’re the first and second argument respectively.

When to use map state to props and map dispatch to props in React Redux

Example Code:

import React from "react";
import { Provider, connect } from "react-redux";
import { createStore } from "redux";
import ReactDOM from "react-dom";

function counterReducer(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    default:
      return state;
  }
}

const store = createStore(counterReducer);

class App extends React.Component {
  onClick() {
    this.props.increment();
  }
  render() {
    const { count } = this.props;
    return (
      <>
        <button onClick={this.onClick.bind(this)}>Increment</button>
        <p>{count}</p>
      </>
    );
  }
}

const mapDispatchToProps = dispatch => {
  return {
    increment: () => dispatch({ type: "INCREMENT" })
  };
};
const mapStateToProps = state => ({
  count: state
});

App = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

In the code, we have an app that shows a number going up as we click the Increment button.

The first step to connect the store to our React app is to wrap the Provider component around our whole app.

To do this we have written the following:

<Provider store={store}>
  <App />
</Provider>

Then we define the mapStateToProps and mapDispatchToProps functions as follows:

const mapDispatchToProps = dispatch => {
  return {
    increment: () => dispatch({ type: "INCREMENT" })
  };
};
const mapStateToProps = state => ({
  count: state
});

In mapStateToProps we return a object to map the state object to a React component prop name as indicated in the property name. The state is the state stored in the Redux store.

So we mapped state to the prop count .

In mapDispatchToProps , we get the dispatch parameter, which is a function used to dispatch our action to the store, and return an object with the name for the function we can access from the props to call and dispatch the action.

So in mapDispatchToProps , increment is our function name. We can call it by running this.props.increment in our App component.

increment is a function that runs dispatch({ type: “INCREMENT” }) .

Then in our App component, we define the onClick method to call this.props.increment to dispatch the ‘INCREMENT’ action to our counterReducer via our Redux store and increase the state by 1.

Then since we have mapStateToProps , the latest value is being observed by App and the latest value is available via this.state.count as indicated in mapStateToProps .

Then when we click the Increment button, we’ll get the number going up by 1.

This will happen with every click.

We pass in the mapStateToProps and mapDispatchToProps to map the store’s state to our component’s props and map our dispatch function call to our props respectively.

Hope this article on When to use map state to props and map dispatch to props in React Redux is useful to you. To read about childen props, please visit How to use Chidren Props in ReactJS

How to use Chidren Props in ReactJS

Hello People. This article is about how to use Chidren Props in ReactJS. The { props.children } property allows you to create a generic template component that can be modified by the parent when it is invoked. This means that a parent component can pass whatever is needed in the child component, even generated layout features that can then be rendered by the child.

In the parent component, import the child component, but instead of invoking it with a self-closing tag, use an standard open/closing tag. The information that you want to pass through props — in addition to the standard implementation of passing props — is placed between the opening and closing tags of the child component.

Implementing <ParentComponent />: The <ParentComponent /> defines a paragraph that will be passed down to the <ChildComponent /> as props.
Implementing <ChildComponent />: In the ChildComponent. { props.children } will render any data that has been passed down from the parent, allowing the ParentComponent to customize the contents of the ChildComponent.
Here we see that the result of content being passed to a child from the parent component, that is then rendered in the child.

Hope this article on How to use Chidren Props in ReactJS is useful to you. To read about List.Accordion, please visit How to use List.Accordion in React Native and Expo Projects

Sources:

https://stackoverflow.com/questions/49706823/what-is-this-props-children-and-when-you-should-use-it

https://reactjs.org/docs/composition-vs-inheritance.html

https://daveceddia.com/pluggable-slots-in-react-components/?utm_campaign=0731slots

Navigation

× Contact Us