Reputation: 23
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>
)
}
Upvotes: 2
Views: 8400
Reputation: 11797
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>
)
}
Upvotes: 4
Reputation: 33
So the filtering logic looks fine but what are you missing is to set the search input state.
Change this line
<input type="text"></input>
to this:
<input type="text" value={search} onChange={(e) => setSearch(e.target.value)}></input>
Upvotes: 1