I'm new to React. I'm building a small function component that renders the weaknesses of a Pokemon.
It takes the type of the Pokemon stored in the state (pokemonState.types) as an array of objects for each type, compare the type to a JSON file containing all the type effectiveness (see below).
types_data.json
"electric": {
"attack": {
"double": ["flying", "water"],
"half": ["dragon", "electric", "grass"],
"zero": ["ground"]
},
"defense": {
"half": ["electric", "flying", "steel"],
"double": ["ground"],
"zero": []
}
To get the data I want, I need to do several iterations and I noticed my component only renders when I specify the return keyword and wrap my element in a HTML tag.
Function that doesn't render anything (but console.log doesn't return undefined)
const pokemonTypeChart = () => {
if (!_.isEmpty(pokemonState)) {
const allTypes = Object.entries(types_data);
const typeEffectiveness = allTypes.map(([key, value]) => {
pokemonState.types.map((el) => {
if (el.type.name === key) {
console.log(key, value);
return <p>{el}</p>;
}
});
});
return (
<div>
<h1>Test</h1>
<p>{typeEffectiveness}</p>
</div>
);
}};
Function that works well:
const pokemonTypeChart = () => {
if (!_.isEmpty(pokemonState)) {
const allTypes = Object.entries(types_data);
return (
<div>
<h1>Type Effectiveness</h1>
{allTypes.map(([key, value]) => {
return (
<>
{pokemonState.types.map((el, i) => {
if (el.type.name === key)
return <h3 key={i}>{value.defense.double}</h3>;
})}
</>
);
})}
</div>
);
}};
My question are:
- For the function that doesn't render anything, the problem is that I don't use return after each iteration right?
- Is my second function good practice in this scenario? is there a cleaner way I should I have wrote it?
Thanks for your help.