Build a Fruit Search App - Step 12

Tell us what’s happening:

What’s wrong here any help would be useful?

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: index.jsx */
{/* User Editable Region */}

// Sample data: list of fruits
const fruits = [
  { name: 'Apple' },
  { name: 'Banana' },
  { name: 'Cherry' },
  { name: 'Date' },
  { name: 'Grape' },
  { name: 'Mango' },
  { name: 'Orange' },
  { name: 'Peach' },
  { name: 'Strawberry' }
];

// Function to filter fruits based on a query.
// If the query is empty, return all fruits.
function searchFruits(query) {
  if (!query) return fruits.slice();
  query = query.trim().toLowerCase();
  return fruits.filter(fruit => fruit.name.toLowerCase().includes(query));
}

// Function to render results in #results container
function renderResults(results) {
  const container = document.getElementById('results');
  if (!container) {
    console.warn('#results element not found in the document.');
    return;
  }

  container.innerHTML = '';

  if (!Array.isArray(results) || results.length === 0) {
    const p = document.createElement('p');
    p.textContent = 'No results found';
    container.appendChild(p);
    return;
  }

  results.forEach(fruit => {
    const p = document.createElement('p');
    p.className = 'result-item';
    p.textContent = fruit.name;
    container.appendChild(p);
  });
}

// Set up search input and event listener
document.addEventListener('DOMContentLoaded', () => {
  const searchInput = document.getElementById('search');

  if (searchInput) {
    searchInput.addEventListener('input', function () {
      const query = searchInput.value;
      const results = searchFruits(query);
      renderResults(results);
    });

    // Initial render (show all fruits)
    renderResults(fruits);
  } else {
    // If there's no search input, still attempt an initial render
    renderResults(fruits);
  }
});

{/* User Editable Region */}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36

Challenge Information:

Build a Fruit Search App - Step 12

Step 12 is about the FruitsSearch() function, which isn’t part of the code you provided. Can you provide the code you tried?


const fruits = [
  { name: 'Apple' },
  { name: 'Banana' },
  { name: 'Cherry' },
  { name: 'Date' },
  { name: 'Grape' },
  { name: 'Mango' },
  { name: 'Orange' },
  { name: 'Peach' },
  { name: 'Strawberry' }
];

 */
function searchFruits(query) {
const q = (query || '').trim().toLowerCase();
if (q === '') return fruits.slice();
return fruits.filter(f => f.name.toLowerCase().includes(q));
}
 *
 * Accepts results as an array of objects ({ name }) OR strings.
 */
function renderResults(results) {
const container = document.getElementById('results');
if (!container) {
return;
  }
container.innerHTML = '';

if (!Array.isArray(results) || results.length === 0) {
const p = document.createElement('p');
p.textContent = 'No results found';
container.appendChild(p);
return;
  }

results.forEach(item => {
const name = (typeof item === 'string') ? item : (item && item.name) ? String(item.name) : '';
const p = document.createElement('p');
p.className = 'result-item';
p.textContent = name;
container.appendChild(p);
  });
}

document.addEventListener('DOMContentLoaded', () => {
const searchInput = document.getElementById('search');

const initialRender = () => {
const q = searchInput ? searchInput.value : '';
renderResults(searchFruits(q));
  };

if (searchInput) {
searchInput.addEventListener('input', () => {
const q = searchInput.value;
renderResults(searchFruits(q));
    });
  }

initialRender();
});

{
window.fruits = fruits;
window.searchFruits = searchFruits;
window.renderResults = renderResults;
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Fruit Search (React)</title>
<style>
.result-item { margin: 4px 0; }
</style>
</head>
<body>
<input type="text" id="search" placeholder="Search fruits..." />
<!-- The #results element described in the instructions -->
<div id="results-root"></div>

<!-- React + ReactDOM + Babel (for quick demo) -->
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<!-- App using JSX; it mounts into #results-root and uses the #search input -->
<script type="text/babel">
    const { useState, useEffect } = React;

    // Sample data: list of fruits
    const fruits = [
      { name: 'Apple' },
      { name: 'Banana' },
      { name: 'Cherry' },
      { name: 'Date' },
      { name: 'Grape' },
      { name: 'Mango' },
      { name: 'Orange' },
      { name: 'Peach' },
      { name: 'Strawberry' }
    ];

    // Filter helper
    function searchFruits(query) {
      const q = (query || '').trim().toLowerCase();
      if (!q) return fruits.slice();
      return fruits.filter(f => f.name.toLowerCase().includes(q));
    }

    // React component that renders into the #results-root element.
    // It reads the input with id="search" and displays results inside a div with id="results".
    function FruitSearchApp() {
      const [query, setQuery] = useState('');
      const [results, setResults] = useState(fruits);

      useEffect(() => {
        // If an external input with id="search" exists, mirror its value into React state.
        const externalInput = document.getElementById('search');
        if (!externalInput) return;

        // Initialize from current input value
        setQuery(externalInput.value);
        setResults(searchFruits(externalInput.value));

        // Handler to update React state when the external input changes
        const handler = (e) => {
          const val = e.target.value;
          setQuery(val);
          setResults(searchFruits(val));
        };

        externalInput.addEventListener('input', handler);
        return () => externalInput.removeEventListener('input', handler);
      }, []);

      // Ternary operator inside the #results element as requested.
      return (
        <div id="results">
          {results.length > 0
            ? results.map(item => (
                // key attribute included for each mapped <p>
                <p key={item.name} className="result-item">{item.name}</p>
              ))
            : <p>No results found</p>
          }
        </div>
      );
    }

    // Mount the React component into the designated container
    const container = document.getElementById('results-root');
    const root = ReactDOM.createRoot(container);
    root.render(<FruitSearchApp />);
</script>
</body>
</html>
body {
  font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f4;
}

#search-container {
text-align: center;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

#search-input {
padding: 10px;
width: 80%;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 10px;
}

#results {
text-align: left;
max-height: 150px;
overflow-y: auto;
}
.result-item {
padding: 5px;
border-bottom: 1px solid #ddd;
}

Here’s my updated code as requested.

could you post it as a single code block? having each line be its own code block make reading harder

Fruit Search (React) .result-item { margin: 4px 0; }

body {

font-family: Arial, sans-serif;

display: flex;

justify-content: center;

align-items: center;

height: 100vh;

background-color: #f4f4f4;

}

#search-container {

text-align: center;

background: white;

padding: 20px;

border-radius: 10px;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

}

#search-input {

padding: 10px;

width: 80%;

border: 1px solid #ccc;

border-radius: 5px;

margin-bottom: 10px;

}

#results {

text-align: left;

max-height: 150px;

overflow-y: auto;

}

.result-item {

padding: 5px;

border-bottom: 1px solid #ddd;

}

const fruits = [

{ name: ‘Apple’ },

{ name: ‘Banana’ },

{ name: ‘Cherry’ },

{ name: ‘Date’ },

{ name: ‘Grape’ },

{ name: ‘Mango’ },

{ name: ‘Orange’ },

{ name: ‘Peach’ },

{ name: ‘Strawberry’ }

];

*/

function searchFruits(query) {

const q = (query || ‘’).trim().toLowerCase();

if (q === ‘’) return fruits.slice();

return fruits.filter(f => f.name.toLowerCase().includes(q));

}

*

* Accepts results as an array of objects ({ name }) OR strings.

*/

function renderResults(results) {

const container = document.getElementById(‘results’);

if (!container) {

return;

}

container.innerHTML = ‘’;

if (!Array.isArray(results) || results.length === 0) {

const p = document.createElement(‘p’);

p.textContent = ‘No results found’;

container.appendChild(p);

return;

}

results.forEach(item => {

const name = (typeof item === ‘string’) ? item : (item && item.name) ? String(item.name) : ‘’;

const p = document.createElement(‘p’);

p.className = ‘result-item’;

p.textContent = name;

container.appendChild(p);

});

}

document.addEventListener(‘DOMContentLoaded’, () => {

const searchInput = document.getElementById(‘search’);

const initialRender = () => {

const q = searchInput ? searchInput.value : ‘’;

renderResults(searchFruits(q));

};

if (searchInput) {

searchInput.addEventListener(‘input’, () => {

const q = searchInput.value;

renderResults(searchFruits(q));

});

}

initialRender();

});

{

window.fruits = fruits;

window.searchFruits = searchFruits;

window.renderResults = renderResults;

}

I think you need to wrap in round parentheses this one too

When you enter a code block into a forum post, please precede it with three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add the backticks.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

item does not have a name property, item is a string, try solving with that in mind