I’m building a Pokémon team generator and the user should be able to use ReactSearchAutocomplete before I fetch data from an external API. I wrote an external file including information like pokemon name and id, it looks like this:
const pokemonlist = [
{
name: "bulbasaur",
id: 1,
},
{
name: "ivysaur",
id: 2,
},
{
name: "venusaur",
id: 3,
},
{
name: "terapagos",
id: 1024,
},
{
name: "pecharunt",
id: 1025,
},
];
export default pokemonlist;
Since the file is more than 4100 lines long I shortened it here so that it’s easier to read for you.
In my second file for the actual Searchbar Component I wrote this:
import pokemonlist from "./pokemon/pokemonlist";
import { ReactSearchAutocomplete } from "react-search-autocomplete";
export default function SearchbarAutocomplete() {
const handleOnSearch = (string, results) => {
// console.log(string, results);
};
const handleOnHover = (result) => {
console.log(result);
};
const handleOnSelect = (item) => {
console.log(item);
};
const handleOnFocus = () => {
// console.log("Focused");
};
const formatResult = (item) => {
return (
<>
<span style={{ display: "block", textAlign: "left" }}>
#{item.id} {item.name}
</span>
</>
);
};
return (
<ReactSearchAutocomplete
items={pokemonlist}
onSearch={handleOnSearch}
onHover={handleOnHover}
onSelect={handleOnSelect}
onFocus={handleOnFocus}
autoFocus
formatResult={formatResult}
placeholder="Search Pokemon"
/>
);
}
Doing it like this the pokemonlist is not found. There’s no error in my console but I get the fallback “No results”. I also tried using a named export, same thing happens.
If I place the const inside the SearchbarAutocomplete function, everything works as expected, it looks like this:
import pokemonlist from "./pokemon/pokemonlist";
import { ReactSearchAutocomplete } from "react-search-autocomplete";
export default function SearchbarAutocomplete() {
const pokemonlist = [
{
name: "bulbasaur",
id: 1,
},
{
name: "ivysaur",
id: 2,
},
{
name: "venusaur",
id: 3,
},
{
name: "terapagos",
id: 1024,
},
{
name: "pecharunt",
id: 1025,
},
];
const handleOnSearch = (string, results) => {
// console.log(string, results);
};
const handleOnHover = (result) => {
console.log(result);
};
const handleOnSelect = (item) => {
console.log(item);
};
const handleOnFocus = () => {
// console.log("Focused");
};
const formatResult = (item) => {
return (
<>
<span style={{ display: "block", textAlign: "left" }}>
#{item.id} {item.name}
</span>
</>
);
};
return (
<ReactSearchAutocomplete
items={pokemonlist}
onSearch={handleOnSearch}
onHover={handleOnHover}
onSelect={handleOnSelect}
onFocus={handleOnFocus}
autoFocus
formatResult={formatResult}
placeholder="Search Pokemon"
/>
);
}
But >4000 lines of text… I’d really like to separate these information from my actual code. Can you help me here please? What do I miss?