Filter Array Of Objects Based On Input Field In React
Got in a rather troublesome situation I have an array of objects
[
{
"title":"placeholder",
"text":"placeholder"
},
{
"title":"test",
"text":"placeholder"
},
{
"title":"javascript",
"text":"placeholder"
}
]
I am displaying them in a div,but thats not important I got an input field which users should type in title's and as they type the array should only show matching object. Inputing java would show the javascript titled object
I need to somehow change the array so it doesnt display anything but the entered title and if the input is empty shows the whole array
I am using React but i can only use hooks So i copy the json
var [arrayOfObjects, setArray] = useState(Json)
the Json is imported from a local file arrayOfNotes is the array that i need to change pointing out so its easier to understand
ty in advance
Answer
The array filter method is what you're looking for.
Here's what your component might looks like.
const List = ({ data }) => {
const [value, setValue] = useState('')
return (
<div>
<input
type="text"
value={value}
onChange={e => setValue(e.target.value)}
/>
{data
.filter(item => {
if (!value) return true
if (item.title.includes(value) || item.text.includes(value)) {
return true
}
})
.map(item => (
<div>
<h1>{item.title}</h1>
<p>{item.text}</p>
</div>
))
}
</div>
)
}
And you pass your json data to that component
<List data={Json} />
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM