Tag: JavaScript

  • Optional Chaining in ES7

    Optional Chaining in ES7

    What is optional chaining?
    Optional chaining allows you to access the value of a property in a nested object without the need to validate each object key/value in the chain.

    I will try to explain it with an example.

    I have an object, the value I have is deep inside a nested object.

      let data = {
        user: {
          feed: {
            edgeReels: {
              tray: {
                node: {
                  dataExpiryDays: 2
                }
              }
            }
          }
        }
      };

    I want to check the value of dataExpiryDays and do something.

    We can do this like this

    if(data.user.feed.edgeReels.tray.node.dataExpiryDays) {
        // do something
    }

    Wait…. anyone using JavaScript might know the potential dangers of this approach. If any of the nested object is not available or null the above line of code will break.

    Example if the key edgeReels is not available, you will get an error like Cannot access tray of undefined .

    So we write the above code like this.

      if (
        data &&
        data.user &&
        data.user.feed &&
        data.user.feed.edgeReels &&
        data.user.feed.edgeReels.tray &&
        data.user.feed.edgeReels.tray.node &&
        data.user.feed.edgeReels.tray.node.dataExpiryDays
      ) {
        // do something
      }

    See you need to do a check for every keys in each nested level.

    To avoid these kind of checks, there was new feature proposal called Optional Chaining to be included in ES7. The proposal is now in Stage 4 (5/31/2020 – when I was writing this.) . See the proposal here.

    The Optional Chaining operator ?.

    With optional chaining operator we can write the above if condition like this.

    if(data?.user?.feed?.edgeReels?.tray?.node?.dataExpiryDays) {
        // do something
    }

    If any of the keys are missing subsequent checks are not done and the if condition fails.

    Question 1: Can we validate an array position using Optional chaining?

    Yes. like this

    if(data?.nameArray?.[0]) {
     // nameArray has index 0
    }

    Now the big questions.

    1. Can we use Optional chaining in my JavaScript project?
    2. Can we use Optional chaining in my React App?

    Can we use Optional chaining in my JavaScript project?

    No. As Optional chaining is still in proposal stage, most browsers will NOT have full support implemented. So I recommend not to use it unless you add polyfills. As of 8/8/2022 all latest browser versions support optional chaining. The latest browser support can be viewed here in CanIUse website.

    Can we use Optional chaining in my React App?

    React CRA uses Babel. Babel is a JavaScript transcompiler  which makes new/next generation JavaScript features backward compatible with all browsers(don’t expect IE older versions).

    So if you use React or Gastby or any other JavaScript project uses Babel 7.8 or above versions you are good to use Optional Chaining. If you are using React CRA check Babel version inside node-modules/@babel/core/package.json or check for a folder plugin-proposal-optional-chaining inside node-modules/@babel/

    Check it out and post your comments if any.

    Happy coding…. 🍺

  • India COVID-19 dashboard

    India COVID-19 dashboard

    Created a dashboard for WhatIndiaThinks.com on Coronavirus COVID-19. This dashboard is specifically for India cases.

    Check out the dashboard

    Tech stack

    • React JS
    • Sass
    • Node JS
    • Material UI
    • Recharts / D3
    • PHP
    • Deployed on Apache server
  • Recharts show legend on top of chart

    Recharts show legend on top of chart

    Use below to move Recharts legend to top of the graph. In fact you can position the legends any where (top, right, bottom , left, left top, left middle etc) you like. I have added few code samples for that corresponding images. Please go through it.

    <Legend layout="horizontal" verticalAlign="top" align="center" />

    I am using a Pie chart, so the above code will show legend on top of the chart and it looks like this.

    Lets try few other styles

    <Legend verticalAlign="middle" align="center" />
    <Legend verticalAlign="bottom" align="center" />
    <Legend layout="vertical" verticalAlign="middle" align="right" />
    <Legend layout="vertical" verticalAlign="top" align="right" />

    The overall code looks like this.

  • JavaScript – Find unique array

    Here I will explain how to find an unique array from an array which has duplicates.

    There are different methods to find the unique elements in an array. Here lets use ES6 functions reduce and find.

    function uniqueArray(array) {
      var newUniqueArray = array.reduce((accumulator, currentValue) => {
        if (!accumulator.find(arrayItem => arrayItem === currentValue)) {
          accumulator.push(currentValue);
        }
        return accumulator;
      }, []);
    
      return newUniqueArray;
    }

    Checkout the working code sample below

    See the Pen Unique array using reduce and find by Kiran (@kiranvj) on CodePen.

    https://static.codepen.io/assets/embed/ei.js

    Happy coding…..

  • Object key as variable

    Create a JavaScript object with dynamic keys, that is key name will come from variable.

    I want to create an object like this.

    let details = { car: "red" }

    Here car is the key and red is the value, Now I need the object key car to come from a variable called item.

    In ES5 we do it like this

    var details = {};
    var item = "car";
    details [item] = "red"; // now the object will be { car : "red" }

    But in ES6 we can do like this.

    let item = "car";
    let details = { [item] : "red" }; 
    // now the details object will be { car : "red" }

    Hope this helps 🧡

  • Warning when using withRouter with new React Context API

    React version : > 16.6

    Getting this warning when using Context API with withRouter

    Warning: withRouter(Home): Function components do not support contextType.

    This happens when use the React context API like this

    Home.contextType = AppContext;
    export default withRouter( Home ); // warning is triggering here

    To fix this we need to use hoist-non-react-statics to automatically copy all non-React static methods. I used hoist-non-react-statics version 3.1.0.

    Install `hoist-non-react-statics` using command `npm i hoist-non-react-statics` Link here

    Import it in your file

    import hoistNonReactStatics from 'hoist-non-react-statics';

    After importing, export your component like this

    Home.contextType = AppContext;
    export default hoistNonReactStatics( Home, withRouter ( Home) );

    Related reading here, here and here

  • Add attributes with empty values in ReactJS

    There are times when you want to add html tag attributes in a React app.

    We normally add attributes based on some logic, for example if some state value is true set the value of the attribute as something.

    Example

    <div className={ this.state.isRisk ? "danger" : "normal">...</div>

    This will be either rendered as

    <div class="danger">...</div> or div class="normal">...</div> 

    based on the state value isRisk

    In the above case there is a value for the attribute, that is class="danger" . Sometimes you don’t want to have any value for the attribute. I was using a third party library which checks only if the attribute is present, it does not care about the attribute values.

    So I tried something like this.

    <div { this.state.isPrint ? data-is-print : null } >...</div> 

    I am using vscode editor and it will immediately throw the below error.


    vscode error when trying to add attribute with empty values

    I need the output like 

    <div data-is-print>...</div>

    This is how to do that.

    Have a variable like this.

    let dataIsPrint = this.state.isPrint ? { "data-is-print" : "" } : {};

    In the render() use like this.

    <div { ...dataIsPrint } > Some text </div>

    The rendered code will look like this.

    <div data-is-print> Some text </div>

    The same method can be used to add checked and disabled attributes in form inputs.

    Hope this helps… 🍹

  • React — How to pass event or any other details to onClick or other event handlers

    We may need to get a the event details in a onClick or onChange event handler.

    Normal event handler will look like this.

    <button onClick={ this.handleClick } >Save </button>
    <input type="text" onChange={ this.handleChange } />

    In the above case we are not passing any event details to handler function.

    Consider the input example above, we need to get the input value in event handler, how do we do it? We need to pass the event details to the handler function. This is how to do it.

    <input type="text" onChange={ (evt) => this.handleChange(evt) } />

    The handleChange function

    handleChange(evt) {
    // ---------^ this variable will have the event details. //get the value of the input box
    let value = evt.target.value;}

    Similarly we can also send any other information to the event handler function.

    render() {
    let name = "Sput"; return <input type="text" onChange={ (evt, name) => this.handleChange(evt, name) } />
    }

    The handleChange function will look like this.

    handleChange(evt, name) {
    // --------------^ this variable will have the name details.
    }

    Hope this helps 🍺

  • Convert JavaScript object to FormData

    Scenario: I was using Formik in React. There was a need to convert formik values to FormData to send to API as post.

    This is how it was done.

    // A sample object  
    let values = { name : 'Kiran', location: 'Sedona' };
    
    let data = new FormData();
    for (let key in values) {
        data.append(key, values[key]);
    }
    console.log(data);
  • How to check if a JavaScript object is empty

    function isObjectEmpty(object)
    {
      var isEmpty = true;
      for(keys in object)
      {
         isEmpty = false;
         break; // exiting since we found that the object is not empty
      }
      return isEmpty;
    }

    Example:

    var myObject = {}; // Object is empty
    var isEmpty  = isObjectEmpty(myObject); // will return true;
    
    // populating the object
    myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 
    
    // check if the object is empty
    isEmpty  = isObjectEmpty(myObject); // will return false;
Design a site like this with WordPress.com
Get started