Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

javascript - Make a search filter with react and typescript

  1. Hi I would really like some help on how to make a search filter. I wanna be able to type in some text in the input field so the ul list filter with the same letters.
interface ICrypto {
  id: string;
  name: string;
}

const defaultProps:ICrypto[] = [];

const Dashboard: React.FC = () => {
  const [crypto, setCryptos]: [ICrypto[], (posts: ICrypto[]) => void] = React.useState(defaultProps);
  const [search, setSearch]: [string, (search: string) => void] = React.useState("");

  const handleChange = (e: { target: { value: string; }; }) => {
    setSearch(e.target.value);
  };

  const filteredCoins = crypto.filter(crypto =>
    crypto.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="App">
     <ul className="posts">
       <input type="text"></input>
         {crypto.map((crypto) => (
           <li key={crypto.id}>
            <h3>{crypto.id}</h3>
              <p>{crypto.current_price}</p>
              <p>{crypto.symbol}</p>
                <img src={crypto.image} alt="image" />
           </li>
         ))}
     </ul>
  {error && <p className="error">{error}</p>}
</div>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
const Dashboard: React.FC = () => {
  const [crypto, setCryptos]: [ICrypto[], (posts: ICrypto[]) => void] = React.useState(defaultProps);
  const [search, setSearch]: [string, (search: string) => void] = React.useState("");

  const handleChange = (e: { target: { value: string; }; }) => {
    setSearch(e.target.value);
  };

  return (
    <div className="App">
     <ul className="posts">
       <input type="text" onChange={handleChange} />
         {crypto.map((crypto) => {
             if (search == "" || crypto.name.toLowerCase().includes(search.toLowerCase())) {
                 return (
                     <li key={crypto.id}>
                         <h3>{crypto.id}</h3>
                         <p>{crypto.current_price}</p>
                         <p>{crypto.symbol}</p>
                         <img src={crypto.image} alt="image" />
                     </li>
                 );
             }
             return null;
         )}
     </ul>
     {error && <p className="error">{error}</p>}
   </div>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...