DEV Community

ryanAllMad
ryanAllMad

Posted on

Array Methods in React

Hey and welcome! Thanks so much for stopping by. If you are looking to learn how to work with array methods beyond map in React such as filter(), sort(), or some() you’re in the right place! I’ll show you how to use array methods in React.

In this article we are going to take a React List that’s mapped out, filter through it with the Array.filter() method, then we’ll sort our React List with Array.sort() and finally we’ll test the contents of the list using the Array.some() method.

In this project we're using React + Typescript, but if you have no experience with Typescript that's okay. Just change the file extensions from .ts to .js and .tsx to .jsx 👍 I've left comments for the code below to know what you can ignore if you're using a regular create-react-app application.

To get the most out of this article, check out the build here and check out the source code here.

To get started

Open your terminal in VSCode and run:

npx create-react-app my-app

Or if you’re using Typescript:

npx create-react-app my-app --template typescript

File Structure

In the /src directory create a new folder called /components

Inside the components folder create three files:

  • BestNovel.tsx
  • Button.tsx
  • List.ts

The List Data

The list data is housed inside our components folder. Because there is no JSX in this file, this file ends with .ts. This file houses our List which is an array of objects. Each object stores data about Nebula Award Winning Novels written by a woman.

// If you aren't using Typescript
// Ignore the interface and ': IList[]' from the List export below

export interface IList {
    Title: string,
    Author: string,
    Year: number,
    id: number
}
// Female Nebula Award Winners for Best novel:
export const List: IList[] = [
    {Title: 'The Left Hand of Darkness', Author: 'Ursula K. Le Guin', Year: 1969, id: 1},
    {Title: 'The Dispossessed', Author: 'Ursula K. Le Guin', Year: 1974, id: 2},
    {Title: 'Dreamsnake', Author: 'Vonda McIntyre', Year: 1978, id: 3},
    {Title: 'The Falling Woman', Author: 'Pat Murphy', Year: 1987, id: 4},
    {Title: 'Falling Free', Author: 'Lois McMaster Bujold', Year: 1988, id: 5},
    {Title: 'The Healer\'s War', Author: 'Elizabeth Ann Scarborough', Year: 1989, id: 6},
    {Title: 'Tehanu: The Last Book of Earthsea', Author: 'Ursula K. Le Guin', Year: 1990, id: 7},
    {Title: 'Doomsday Book', Author: 'Connie Willis', Year: 1992, id: 8},
    {Title: 'Slow River', Author: 'Nicola Griffith', Year: 1996, id: 9},
    {Title: 'The Moon and the Sun', Author: 'Vonda McIntyre', Year: 1997, id: 10},
    {Title: 'Parable of the Talents', Author: 'Octavia E. Butler', Year: 1999, id: 11},
    {Title: 'The Quantum Rose', Author: 'Catherine Asaro', Year: 2001, id: 12},
    {Title: 'The Speed of Dark', Author: 'Elizabeth Moon', Year: 2003, id: 13},
    {Title: 'Paladin of Souls', Author: 'Lois McMaster Bujold', Year: 2004, id: 14},
    {Title: 'Powers', Author: 'Ursula K. Le Guin', Year: 2008, id: 15},
    {Title: 'Blackout/All Clear', Author: 'Connie Willis', Year: 2010, id: 16},
    {Title: 'Among Others', Author: 'Jo Walton', Year: 2011, id: 17},
    {Title: 'Ancillary Justice', Author: 'Ann Leckie', Year: 2013, id: 18},
    {Title: 'Uprooted', Author: 'Naomi Novik', Year: 2015, id: 19}
]
Enter fullscreen mode Exit fullscreen mode

We’re importing this List into our BestNovel.tsx file at the top.

Import Statements

At the top of our BestNovel.tsx file we’re importing the following:

import React, { useState } from 'react'
import Button from './Button'
import { List } from './List'
Enter fullscreen mode Exit fullscreen mode

At the top of our Button.tsx component we’re just importing React:

import React from 'react'
Enter fullscreen mode Exit fullscreen mode

Finally, at the top of our App.tsx component, we’re importing the following:

import React from 'react';

import BestNovel from './components/BestNovel';

import './App.css'
Enter fullscreen mode Exit fullscreen mode

State

Back in our BestNovel.tsx component, we’re using two pieces of state the newList and the newTitle. We’ll update our App component based on these pieces of state.

const BestNovel = () => {    
    const [newList, setNewList] = useState([<li></li>])
    const [newTitle, setNewTitle] = useState('')

// onClick handlers here

// return jsx here
}
Enter fullscreen mode Exit fullscreen mode

In the BestNovel.tsx return statement below, we can see where each piece of state is being declared.


return (
        <>
        <h1>Novels by Women who've won a Nebula Award:</h1>
        <ul>
            {List.map(list => (
                <li key={list.id}>
                    <span className='author'>{list.Author} - </span>
                    <span className='title'>{list.Title} - </span>
                    <span className='year'>{list.Year} </span>
                    </li>
            ))}
        </ul>
        <>
        <div className='filtered-list'>
            <h2>{`${newTitle}`}</h2>
            <ul>{newList}</ul>
            </div>
        <div className='buttons-bar'>
            <Button onClick={handleFilter} name="Filter Novels that won in the 2000's" />
            <Button onClick={handleSort} name='Sort the authors by first name' />
            <Button onClick={handleSome} name="Some Author's names Ursula exist" />
        </div>
        </>
        </>
    )
Enter fullscreen mode Exit fullscreen mode

In our onClick handlers we are going to change the state of our newList component from an empty list item to whichever list we’ll be returning. We are also updating the newTitle piece of state within each handler as well.

The App Component

The App component is simply putting out the BestNovel.tsx component. This full code is below:

import React from 'react';
import BestNovel from './components/BestNovel';
import './App.css'

function App() {
  return (
    <div className="App">
      <BestNovel />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

The meat of our work is within the BestNovel.tsx component.

The Buttons

We have a Button.tsx component in our components folder. That code is below and it’s very basic. It has a name prop for the button label, and an onClick prop for the onClick function.

import React from 'react'


// If you aren't using Typescript
// Ignore the interface and ': React.FC<IButton>' from 
// the Button export below

interface IButton {
    name: string,
    onClick?: () => void
}

const Button: React.FC<IButton> = ({name, onClick}) => {
    return <button onClick={onClick}>{name}</button>
}
export default Button
Enter fullscreen mode Exit fullscreen mode

We’re implementing the button in our BestNovel component like this:

        <div className='buttons-bar'>
            <Button onClick={handleFilter} name="Filter Novels that won in the 2000's" />
            <Button onClick={handleSort} name='Sort the authors by first name' />
            <Button onClick={handleSome} name="Some Author's names Ursula exist" />
        </div>
Enter fullscreen mode Exit fullscreen mode

As you can see we have defined the name prop on each button and have provided onClick handler function calls to each onClick prop.

Filtering the list

Inside our handleFilter() function we do the work of filtering our List component.

    const handleFilter = () => {
       const updatedList = List.filter(list => {
            if(list.Year < 2000) {  
                return
            }
            return list
        })

        setNewList(updatedList.map(list => (
            <li key={list.id}>
                <span className='author'>{list.Author} - </span>
                <span className='title'>{list.Title} - </span>
                <span className='year'>{list.Year} </span>
            </li>
        ))

        )
        setNewTitle("Novel's that won after the year 2000")
    }
Enter fullscreen mode Exit fullscreen mode

We are assigning the value of the filtered list to the updatedList variable. We are doing an early return for any novels awarded before the year 2000. And finally we return the list, or what is left from being filtered out. In our setNewList() function we are mapping through the updatedList variable to update the state of the newList element.

Check out the full post here.

Top comments (0)