Reputation: 1541
I am trying to filter through an array of objects (shown below) that when a user types in an input field, it returns what is searched. I would like to search specific by the name
key and return the corresponding value.
With what I currently have I keep getting the following error:
Objects are not valid as a React child (found: object with keys {type, id, name}). If you meant to render a collection of children, use an array instead.
Initial State:
const [searchTerm, setSearchTerm] = useState('');
const [searchResults, setSearchResults] = useState([]);
Array of Objects:
const people = [
{ name: 'Siri', id: 'siri' },
{ name: 'Alexa', id: 'alexa' },
{ name: 'Google', id: 'google' },
{ name: 'Facebook', id: 'facebook' },
{ name: 'Twitter', id: 'twitter' },
{ name: 'LinkedIn', id: 'linkedin' },
];
useEffect:
useEffect(() => {
const searchResults = processorOptions.filter((o) =>
Object.keys(o).some((k) => o[k].toString().toLowerCase().includes(searchTerm))
);
setSearchResults(searchResults);
}, [searchTerm]);
Search Field:
<input
name='peopleSearch'
id='peopleSearch'
className='form-control'
type='text'
placeholder='Filter by Name'
/>
Displaying Search Results:
{searchResults.map((item) => (
<li>{item}</li>
))}
Upvotes: 0
Views: 458
Reputation: 10873
You need to display the name of the item instead of the item itself:
{searchResults.map((item) => (
<li>{item.name}</li>
))}
Upvotes: 3