Category: JavaScript

  • html-to-draftjs window is not defined error

    html-to-draftjs window is not defined error

    Fix for the issue window is not defined when using html-to-draftjs (npm link )

    The version if the html-to-draftjs is 1.5.0 in nextjs version 10.0.5.

    Below is the error thrown when integrated htmlToDraft in page.

    This issue is fixed using below code at the top of the page just below imports

    let htmlToDraft = null;
    if (typeof window === 'object') {
      htmlToDraft = require('html-to-draftjs').default;
    }

    Hope this helps, happy coding
    🍺🍺

  • Add component prop based on condition in ReactJS

    Add component prop based on condition in ReactJS

    In this article we will discuss how to add or pass a component prop based on a condition.

    Lets have a component named MyButtonComponent that takes a prop name

    <MyButtonComponent name="some text"  />

    Now I need to pass this prop based on a flag called hasName of type Boolean

    We can do this using the spread operator

    <MyButtonComponent {...(hasName ? {name: "some text"} : {} )}  />

    What are we doing?

    We are using spread operator to spread the object {name: “some text”} or an empty object {} based on the value of our flag hasName. To check the condition we are using ternary operator. So the component have name prop or no prop named name

    Hope it helps, happy coding…

    🍺

  • 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…. 🍺

  • ReactJS disable hook eslint warnings

    Think twice when you are trying to disable the hook eslint warnings.

    This is was our prophet Dan Abramov say about it.

    Still if you want to remove the warning add the below like before the violating line

     // eslint-disable-next-line react-hooks/exhaustive-deps 
  • Add Twitter timeline in ReactJS

    Add Twitter timeline in ReactJS

    • Copy the embed code

    The embed code will look like this

    • Goto index.html in your public folder in your ReactJS app. I assume you created the app via CRA
    • Cut the script tag from the embed code inside your head tag in index.html
    • Now we have only the first line that’s the anchor (“a”) tag.
    • Added the anchor tag in you component wherever you need to show it.

    Now we need to load the twitter embed code.

    Do this to load twitter embed code

    For Class component

    componentDidMount: function() {
          window.twttr &&
          window.twttr.widgets &&
          typeof window.twttr.widgets.load === "function" &&
          window.twttr.widgets.load();
    }

    For Functional component, use the useLayoutEffect hook

      useLayoutEffect(() => {
          window.twttr &&
          window.twttr.widgets &&
          typeof window.twttr.widgets.load === "function" &&
          window.twttr.widgets.load();
      });

    Happy coding 🍺

  • 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…..

  • React Table 7.x – Hide Column Header Row

    React Table 7.x – Hide Column Header Row

    Scenario: I am using the new React Table 7x (the headless component). By default there will be a column header for the entire table columns. You can give empty string so that the Header will not be shown. By the problem is that row in html will be still rendered (see the below image). So I want to hide the entire row in html. I am using Material Table with react-table to render the table.

    Row with empty contents

    Solution

    Add a custom key hideHeader:Β false, in the columns variable.

    In the Material table check for this key.

    <TableHead>
            {headerGroups.map((headerGroup) => (
              <TableRow {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column) => {
                  return column.hideHeader === false ? null : (
                    <TableCell {...column.getHeaderProps()}>
                      {column.render('Header')}
                    </TableCell>
                  );
                })}
              </TableRow>
            ))}
          </TableHead>

    This should remove the empty row from html output.

    Happy coding

    🌟 πŸŽ„ πŸŽ… 🦌

  • File upload in Material UI

    For basic file upload you can use the TextField component.

    File upload

    The code will looks something like this.

    <TextField
      name="upload-photo"
      type="file"
    />

    The important thing to note here is you need to set the type props to file

    How do you customize it?

    Customized file input

    As the basic controls are not that fancy we may need to customize it. Since we are using Material UI its straight forward.

    Step 1

    Create an html input with id and file properties. Use style='display:none' as we don’t want to show it.

    The code will look like this

     <input  style={{ display: 'none' }} 
             id="upload-photo"  
             name="upload-photo"  
             type="file"/> 

    Step 2 : Customize it

    Create a label around the input which we created in step 1
    Add Material UI Button or Fab based on how you want your file upload to look.

    Lets try with Button first.

    File upload button

    Inside the label which we created add a Button component. Add the props component with value span. This is very important otherwise the button component will render using the html <button> tag, which fails our file upload.

    For Button component the code will look like this. (working example at the end of post)

    <label htmlFor="upload-photo">
      <input
        style={{ display: 'none' }}
        id="upload-photo"
        name="upload-photo"
        type="file"
      />
    
      <Button color="secondary" variant="contained" component="span">
        Upload button
      </Button>
    </label>;

    Now lets try a different UI

    Custom file upload

    We will use Material UI Fab component for this. The code is very similar to what we have in button example.

    <label htmlFor="upload-photo">
      <input
        style={{ display: 'none' }}
        id="upload-photo"
        name="upload-photo"
        type="file"
      />
    
      <Fab
        color="secondary"
        size="small"
        component="span"
        aria-label="add"
        variant="extended"
      >
        <AddIcon /> Upload photo
      </Fab>
      <br />
      <br />
    
      <Fab color="primary" size="small" component="span" aria-label="add">
        <AddIcon />
      </Fab>
    </label>;
    https://codesandbox.io/embed/eager-euclid-mo7de?fontsize=14&hidenavigation=1&theme=dark

    Hope this helps. Happy coding 🍺

  • Material UI switch with icons

    MUI Switch

    Check the source at my github repo

Design a site like this with WordPress.com
Get started