Logan
Logan

Reputation: 35

Filtering in React.js

I'm fairly new to React and trying to create an App that when you search in the input box it filters out the wrong drivers and only presents you with the correct one. I'm trying to use hooks instead of class components. I have a working project in CodeSandBox: https://codesandbox.io/s/hungry-turing-2n2tj

I've looked at some other answers on stack overflow as well as reading the docs that the React Team has but it is all going above my head. Let me know if there is any more documentation that I can provide! Thanks in advance!

Upvotes: 1

Views: 84

Answers (1)

Moinul Hossain
Moinul Hossain

Reputation: 2206

You are looking for something like this: https://codesandbox.io/s/distracted-frog-d5ocw

Basically pass the drivers to the list from the app component and filter it out based on the search term provided by the searchbox component

Your App.js:



import React from "react";
import "./styles.css";
import CardList from "./card-list";
import SearchBox from "./searchbox";
import allDrivers from "./drivers";

export default function App() {
  const [drivers, setDrivers] = React.useState(allDrivers);

  return (
    <div className="App">
      <h1>F1 Drivers</h1>
      <SearchBox
        onSearch={v => {
          console.log(v);
          if (!v) {
            setDrivers(allDrivers);
            return;
          }
          setDrivers(drivers.filter(d => d.name.toLowerCase().startsWith(v)));
        }}
      />
      <CardList drivers={drivers} />
    </div>
  );
}

your cardlist would look like

import React from "react";

import Card from "./Card";

function CardList(props) {
  return (
    <div className="card-list">
      {props.drivers.map(createCard => (
        <Card
          key={createCard.id}
          name={createCard.name}
          imgURL={createCard.imgURL}
          number={createCard.number}
          team={createCard.team}
          age={createCard.yearsOld.age}
          country={createCard.country}
        />
      ))}
    </div>
  );
}

export default CardList;

and searchbox is simply

import React from "react";
import "./drivers";

function SearchBox(props) {
  return (
    <input
      onChange={e => {
        props.onSearch(e.target.value);
      }}
      type="text"
      // value={props.value}
    />
  );
}

export default SearchBox;

Upvotes: 1

Related Questions