0

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>
))}

1 Answer 1

3

You need to display the name of the item instead of the item itself:

{searchResults.map((item) => (
    <li>{item.name}</li>
))}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.