DEV Community

bmgeier
bmgeier

Posted on

Building a functioning sorter in React

For my second project at Flatiron School I decided to build an archive of emo albums, both allowing me to get back in touch with my high school self and practice building attractive, responsive displays using the React library.

One of the things I wanted to make sure to do was build in a way to sort albums based on the decade in which they were released -- as any emo fan will tell you, after all, there is a big difference between, say, a Braid album from the 90s and a Taking Back Sunday album from just a few years later. Fans of 80s and 90s emo tend to look upon bands that showed up later with scorn, while a lot of fans of 2000s emo don't know much about what came before.

Building this sorter was more difficult than I thought it would be. I kept running into a problem where the sort would work the first time -- say, filtering out all the albums in the database from the 90s -- but on a second attempt to sort it would come up empty.

The first step to fixing this was establishing a second state using the {useState} hook, and putting this in my home component.

Image description

After this, I went into my search component and set up an if/else statement inside my search function:

function handleSearch(event){
    event.preventDefault();
    const decade = event.target.value
    console.log(decade)
    if (decade === "All"){
        setRecords(originalRecords)
    } else {

    const filteredRecords = originalRecords.filter(record => record.decade === decade)
    setRecords(filteredRecords)   
    }
}
Enter fullscreen mode Exit fullscreen mode

Here's the basics of what is happening here -- if you select the "All" option of my dropdown menu, the function uses the "setRecords" setter function to return all records using the "originalRecords" getter variable, which we passed down from the homepage. If any other decade is selected, though, we use a .filter() method to only select the albums from that decade, before using setRecords to make those albums display back in my AlbumContainer component:

const mappedRecords = records.map(record =>{
    return <Album key={record.id} record={record} records={records} setRecords={setRecords} darkMode={darkMode} setDarkMode={setDarkMode}  />
Enter fullscreen mode Exit fullscreen mode

Search is a difficult function to set up for beginners -- in another exercise from this phase, I (along with many of my cohortmates!) struggled to build a real-time search function that would still work when characters were deleted from the search bar. Make sure you're building in logic that accounts for all possibilities!

Top comments (0)