I’m trying to filter the data based on the input in rarity-input. I’ve found that I should use .filter on my map function but I can’t figure out how to do it.
Basically in the rarity-inpupt the user insert a value which is d.id, it can only returns 1 object
<div id='row'>
<input className="rarity-input"/>
<div className="rarity-item">
{props.data
? props.data.map((d, i) => (
<div className='cards'>
<div className="card">
<img src={d.image}/>
<div className="card-body">
<h2>Santa #{d.id}</h2>
<h3>Rarity score: {d.rarity}</h3>
</div>
</div>
</div>
))
: 'Loading...'}
</div>
</div>
[EDIT]
I’m trying something like this
export const Rarity = (props) => {
this.state = {
idTarget : ''
}
function updateInput(event) {
this.setState({idTarget : event.target.value})
}
return (
<div id='rarity' className='text-center'>
<div className='container'>
<div className='col-md-8 col-md-offset-2 section-title'>
<h2>Rarity</h2>
<p>
This tool allows you to check the rarity of your Santa by inserting his serial number !
</p>
<p>
(for example you want the rarity of #14, simply insert : 14)
</p>
</div>
<div id='row'>
<label>
<input className="rarity-input" onChange={this.updateInput}/>
</label>
<div className="rarity-item">
{props.data
? props.data.filter(...).map((d, i) => (
<div className='cards'>
<div className="card">
<img src={d.image}/>
<div className="card-body">
<h2>Santa #{d.id}</h2>
<h3>Rarity score: {d.rarity}</h3>
</div>
</div>
</div>
))
: 'Loading...'}
</div>
</div>
</div>
</div>
)
}
>Solution :
At first, you have to save the user input in a state, after that you have to filter your data based on this state (remember the case that the input is empty it should render the full list.
Note: As you are new to react, I tried to keep it simple but it’s an ugly solution, to enhance it you should use useMemo to save the filtered data, destructure your props and try to keep your code declarative.
import React, { useState } from 'react';
const ComponentName = (props) => {
const [inputValue, setInputValue] = useState();
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div id="row">
<input className="rarity-input" value={inputValue} onChange={handleChange} />
<div className="rarity-item">
{props.data
? props.data
.filter((item) => (inputValue?.length ? item.id === inputValue : true))
.map((d, i) => (
<div className="cards" key={d.id}>
<div className="card">
<img src={d.image} />
<div className="card-body">
<h2>Santa #{d.id}</h2>
<h3>Rarity score: {d.rarity}</h3>
</div>
</div>
</div>
))
: 'Loading...'}
</div>
</div>
);
};