Arrange by date using the isotope-layout feature

I'm struggling to find any guidance on how to implement a date sorting feature using isotope-layout in my Next.js project. Here's the progress I've made so far. The dates are sorting, but it's happening alphabetically. I need assistance with writing this piece of code:

date: function ($elem) { return Date.parse($elem.find('.date').text()); }

const KeyOutcomes = (props) => {
  const isotope = useRef()
  const [sortKey, setSortKey] = useState('date')

  // Setting up an Isotope object with configurations
  useEffect(() => {
    isotope.current = new Isotope('.news', {
      itemSelector: '.newsInner',
      layoutMode: 'fitRows',
      getSortData: {
        header: '.header',
        date: '.date',
      },
    })
    // Cleaning up
    return () => isotope.current.destroy()
  }, [])

  // Handling changes in sort key
  useEffect(() => {
    isotope.current.arrange({ sortBy: `${sortKey}` })
  }, [sortKey])

  const handleSortKeyChange = (key) => () => setSortKey(key)
  return (
    <div className="container">
      <div className="row">
        <div className="col-12">
          <div className="sortAndFilter">
            <ul className="sortFilter">
              <li>Sort By:</li>
              <li
                onClick={handleSortKeyChange('header')}
              >
                Header
              </li>
              <li
                onClick={handleSortKeyChange('date')}
              >
                Date
              </li>
            </ul>
          </div>
          <div className="news">
            <div className="newsInner vege">
              <div className="newsText two">
                <h3 className="header">V News Header</h3>
                <p className="date">02/05/2020</p>
              </div>
            </div>
            <div className="newsInner one">
              <div className="newsText">
                <h3 className="header">D News Header</h3>
                <p className="date">26/05/2020</p>
              </div>
            </div>
            <div className="newsInner one">
              <div className="newsText">
                <h3 className="header">G News Header</h3>
                <p className="date">10/12/2021</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

Answer №1

In order to sort data in Isotope, you have the option to pass a function as the value for date in the getSortData method. This function allows for the retrieval and parsing of date values for proper sorting.

isotope.current = new Isotope('.news', {
    itemSelector: '.newsInner',
    layoutMode: 'fitRows',
    getSortData: {
        header: '.header',
        date: function (newsInnerElem) {
            const dateElem = newsInnerElem.querySelector('.date')
            // Convert date to MM/DD/YYYY format for correct parsing
            const [day, month, year] = dateElem.textContent.split('/')
            return Date.parse(`${month}/${day}/${year}`)
        }
    }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm experiencing difficulty in accessing a Hashmap using a string identifier in Javascript

In my JavaScript code, I have multiple Hashmaps and I am attempting to dynamically load the appropriate map based on the name passed to the function. The issue arises when passing the value as a string because it tries to retrieve keys from the string rat ...

Launch a fresh fancybox once the previous one has exited

I am currently facing an issue with my password change process through a fancybox window. Whenever a user enters the wrong password, a "Wrong Password" iframe opens up. However, the challenge arises when I try to reopen the "Password Change" iframe after c ...

Why does only the last item in JavaScript loops seem to be impacted?

Currently, I am using the gm npm module for image manipulation and have written this code: for(i=0;i < 4;i++){ gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) { console.log(this.outname + " created :: " + arguments[3]) ...

Encountered an undefined error while trying to read promises

I'm attempting to receive a response from a function in order to trigger another function, but I am not receiving the expected response. I encountered the following error message: "TypeError: Cannot read property 'then' of undefined." In my ...

Whenever I attempt to run the NPM install command in the Terminal, it seems to generate multiple errors

I am encountering an issue on my work laptop. I have the latest versions of Angular, Nodejs, Nodesass, and VScode installed in the local environment path. Whenever I download an Angular template from Github and try to do NPM Install, it consistently thro ...

Toggling checkboxes based on user input

My dynamic table is filled with checkboxes that can be checked or unchecked. I have created a jquery script that should change the background color of the table cell whenever a checkbox is modified. However, the script seems to have some bugs and doesn&apo ...

Action creator incomplete when route changes

In my React-Redux application, there is an action creator that needs to make 4 server calls. The first three calls are asynchronous and the fourth call depends on the response of the third call. However, if a user changes the route before the response of t ...

Determine the number of Fridays that fall between two dates using JavaScript or jQuery

Can you help me calculate the total number of a specific day between two given dates? For instance, if I have a start date and end date stored in a variable, I would like to know how many Fridays fall within that timeframe. ...

Error in Chrome Extension Data Type

I am having trouble adding a highlighted red button to YouTube. The code does not seem to be working as expected. manifest.json { "name": "Example", "version": "0.0", "manifest_version": 2, "c ...

Steps for implementing a dynamic animation within a table cell when the value is updated

Incorporating vuetify and nuxt into my web application, how can I implement an animation on a cell when its value changes? I attempted to attach a reference to my table element like so: <v-data-table ref="table" :items="data" :hea ...

Utilizing useState() to manage active link state in Navigation bar component

Learning react and new to the framework. Trying to create a responsive navbar component with material-ui. Works fine on medium devices but struggling with updating active link on smaller devices. Navbar.js ... SideDrawer.js ... C ...

Retrieving a subset of an array column in Sequelize: A comprehensive guide

I am currently working with a table that has an array column named tokens When querying this table using npm sequelize, I sometimes encounter an issue where the tokens column contains up to 20k elements, even though I only need 10 elements from it. In st ...

Unable to make changes to the AWS Dynamo array

I am currently attempting to update a JSON array. I have a table in DynamoDB where I successfully inserted the JSON data using the PUT method. Partition key : _id , Type : S Below is the JSON data that has been saved into the database: { "_id": ...

Collapse all Bootstrap accordions with a single click of a button

Is there a simple way to toggle the collapse/expand functionality of all accordions with just one button click? I attempted to achieve this by using a basic button that would remove the 'active' class and add it back, but unfortunately, it didn&a ...

Performing string operations using an array of strings

I have an array of strings as shown below ["i.was.wen.the.coding", "i.am.wen.to", "i.am.new", "i.am", "i"] Each sentence in the array can be split by a period (.). I am looking to create a logical algorithm pattern to reconstruct a meaningful sentence by ...

What is causing React Js to fail loading css when switching from anchor tag to link tag?

I am learning React and experimenting with creating a basic static website using HTML templates in version ^18.2.0 of React JS. Everything seems to be functioning correctly, however, I have encountered an issue with page refresh. Specifically, when I repla ...

Convert decimal numbers to fixed precision of two decimal places for non-zero decimals

The goal is to achieve two decimal places excluding zeros 1.2234 => 1.22 0.2345 => 0.23 0.02345 => 0.023 (instead of 0.02) 0.0000002345 => 0.00000023 (instead of 0) 0.0000002346545645645646465465 => 0.00000023 (instead of 0) 0.002035 = ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

The Vue.js component fails to display when included within another component

I am experiencing an issue with a menu item not displaying properly in my Vue.js application. The menu item should display the text "This is a menu item", but for some reason it is not being processed and rendered by Vue. These are the main com ...

In JavaScript, I'm facing an issue where I can't seem to use ' ' for line breaks for some reason. It's not functioning as expected, and I'm

It seems that I have been struggling with writing a new line in my code using "\n". Despite multiple attempts, the desired outcome has not been achieved. Below is my source code along with a screenshot of the result: var ary3 = new Array('seve ...