Categories
JavaScript Answers

How to Get Scroll Position with React?

Sometimes, we want to get scroll position with React.

In this article, we’ll look at how to get scroll position with React.

Get Scroll Position with React

To get scroll position with React, we can add a scroll listener to window.

For instance, we write:

import { useEffect, useState } from "react";

export default function App() {
  const [scrollPosition, setScrollPosition] = useState(0);
  const handleScroll = () => {
    const position = window.pageYOffset;
    setScrollPosition(position);
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <div className="App">
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>lorem ipsum {scrollPosition}</p>
        ))}
    </div>
  );
}

to create the scrollPosition state with the useState hook.

Then we add the handleScroll function that takes the scroll position with the window.pageYOffset property.

Then we call setScrollPosition to position, which is assigned to window.payeYOffset.

Next, we call the useEffect hook with a callback that calls window.addEventListener to add the scroll event listener.

We return a function that calls window.removeEventListener to remove the event listener when we unmount the component.

Now when we scroll up and down, we should see the scrollPosition in the rendered text.

Conclusion

To get scroll position with React, we can add a scroll listener to window.

Categories
JavaScript Answers

How to Add Links in Select Dropdown Options with JavaScript?

Sometimes, we want to add links in select dropdown options with JavaScript.

In this article, we’ll look at how to add links in select dropdown options with JavaScript.

Add Links in Select Dropdown Options with JavaScript

To add links in select dropdown options with JavaScript, we can add the change listen to the drop down.

And when a option is selected, we redirect to the URL given by the selected option value.

For instance, we write:

<select>
  <option value="">Pick a site</option>
  <option value="https://www.google.com">x</option>
  <option value="https://www.yahoo.com">y</option>
</select>

to add the select drop down.

Then we write:

const select = document.querySelector("select")
select.onchange = () => {
  if (select.selectedIndex !== 0) {
    window.location.href = select.value;
  }
};

We select the select element with document.querySelector.

Then we set the onchange property to a function that checks if selectedIndex isn’t 0.

If it isn’t, then we get the value and set that as the value of window.location.href to redirect to the selected option.

Now when we select a choice with a URL as its value, we should see the redirect happen.

Conclusion

To add links in select dropdown options with JavaScript, we can add the change listen to the drop down.

And when a option is selected, we redirect to the URL given by the selected option value.

Categories
JavaScript Answers

How to the Get Current Quarter in the Year with JavaScript?

Sometimes, we want to get the current quarter in the year with JavaScript.

In this article, we’ll look at how to the get current quarter in the year with JavaScript.

Get Current Quarter in the Year with JavaScript

To the get current quarter in the year with JavaScript, we can compute the quarter from the date.

For instance, we write:

const getQuarter = (d = new Date()) => {
  let m = Math.floor(d.getMonth() / 3) + 2;
  m -= m > 4 ? 4 : 0;
  const y = d.getFullYear() + (m === 1 ? 1 : 0);
  return [y, m];
}

console.log(getQuarter(new Date(2021, 8, 8)))

We create the getQuarter function that takes the d date object.

In the function body, we call d.getMonth to get the month.

Then we divide that by 3 and add 2.

Next, we shift the m quarter by 4 to get m to be between 1 and 4.

Then we compute the y year by using the d.getFullYear method to get the 4 digit year number.

And then we return 1 or 0 depending on whether m is 1 or not to shift the year according to the definition of the quarter.

The function assumes:

  • Oct-Dec = 1
  • Jan-Mar = 2
  • Apr-Jun = 3
  • Jul-Sep = 4

Then we return y and m in an array.

Therefore, the console log should log [2021, 4] since September is in the 4th quarter.

Conclusion

To the get current quarter in the year with JavaScript, we can compute the quarter from the date.

Categories
JavaScript Answers

How to Get the Extension of an Base64 Image with JavaScript?

Sometimes, we want to get the extension of an base64 image with JavaScript.

In this article, we’ll look at how to get the extension of an base64 image with JavaScript.

Get the Extension of an Base64 Image with JavaScript

To get the extension of an base64 image with JavaScript, we can split the base64 string by the semicolon with split.

Then we get the first item from that.

And, then we call split again to split the returned string by the /.

Then we get the file extension by taking the 2nd element from the returned result.

For instance, we write:

const base64Data = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
const [,type] = base64Data.split(';')[0].split('/');
console.log(type)

to split base64Data by the colon with:

base64Data.split(';')[0]

Then we call split to split the returned string with .split('/').

And finally, we take the 2nd item and assign it to type with the destructruing syntax.

Therefore, we should see that type is 'png' from the console log.

Conclusion

To get the extension of an base64 image with JavaScript, we can split the base64 string by the semicolon with split.

Then we get the first item from that.

And, then we call split again to split the returned string by the /.

Then we get the file extension by taking the 2nd element from the returned result.

Categories
JavaScript Answers

How to Flatten JavaScript Object Keys and Values to a Single Depth Object?

To flatten JavaScript object keys and values to a single depth object, we can create our own function to recursive traverse the object we’re flattening.

For instance, we write:

const obj = {
  name: "test",
  address: {
    personal: "abc",
    office: {
      building: 'random',
      street: 'some street'
    }
  }
}

const flattenObj = (obj, parent, res = {}) => {
  for (const key of Object.keys(obj)) {
    const propName = parent ? parent + '.' + key : key;
    if (typeof obj[key] === 'object') {
      flattenObj(obj[key], propName, res);
    } else {
      res[propName] = obj[key];
    }
  }
  return res;
}

const flattened = flattenObj(obj)
console.log(flattened)

to create the obj object that we want to flatten.

Then we add the flattenObj function that takes the obj, parent, and res objects.

Then we loop through the keys of the object with Object.keys and the for-of loop.

In the loop body, if parent is defined, then we concatenate the parent property name with the key we’re iterating through separated by a dot and assign it to propName.

Otherwise, we set propName to key.

If obj[key] is an object we call flattenObj with obj[key], propName, and res.

res has the flattened object result so far.

Otherwise, we set res[propName] to obj[key].

Once we’re done traversing, we return res.

Next, we call flattenObj with obj and assign it to flattened.

And then we see that flattened is:

{
  "name": "test",
  "address.personal": "abc",
  "address.office.building": "random",
  "address.office.street": "some street"
}
``