Category: JavaScript

  • React environment variables not working or undefined

    In ReactJS environment variables are fetched from .env files. If you set the variable in .env file and your variables returned undefined check the below items.

    Assumption: You have used Create React App (CRA) to bootstrap your application

    1. The .env file should be in the root for you application folder. That is one level above your src folder, the same place where you have your package.json
    2. The variable should be prefixed with REACT_APP_
    3. You need to restart the server to reflect the changes in your code.
    4. You should access the variable in your code like this
      process.env.REACT_APP_SOME_VARIABLE
    5. No need to wrap your variable value in single or double quotes.
    6. Do not put semicolon ; or comma , at the end of each line.

    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);
  • Make React work in IE11

    These are the most probable reasons your Create React App (CRA) is not working in Internet Explorer 11 (IE11)

    1. IE11 is not included in package.json browserList
    2. Promise fails in IE11
    3. fetch function fails in IE11

    Fix

    Update package.json browserList

      "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
      ],

    to this (see minimum IE version changed from <=11 to <=10)

      "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 10",
        "not op_mini all"
      ],

    Add support for fetch

    Add npm packages whatwg-fetch

    npm i whatwg-fetch

    Add support for Promise and other polyfills

    Add npm package core-js and regenerator-runtime

     npm i core-js 
    npm i regenerator-runtime

    Update src/index.js with the newly added packages

    import 'whatwg-fetch';
    import 'core-js/stable';
    import 'regenerator-runtime/runtime';
    

    This should work your CRA in IE11.

  • 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