1

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!

1
  • 1
    Share your code here Commented Jan 10, 2020 at 23:49

1 Answer 1

1

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;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.