mangocaptain mangocaptain - 3 months ago 8
React JSX Question

Check truthiness of props passed from mapStateToProps in functional react redux component

I have 3 components, TypeList, ConnectedType (

=connect(mapStateToProps)(Type
), and Type. Type will receive props from both TypeList (
onClick, name
) passing props to ConnectedType as well as ConnectedType's mapStateToProps (
onMiniPokemonClick, miniPokemon
). How do I do a check to see if
miniPokemon
exists before mapping it out? Is it possible to do logic on a functional component or do I have to make it a class and create a helper function inside?

const Type = ({onClick, name, onMiniPokemonClick, miniPokemon}) => (
<li
onClick={onClick}
>
{name}
<ul>
{
if (miniPokemon) {
miniPokemon.map(function (pokemon, idx) {
return (<MiniPokemon onClick={() => onMiniPokemonClick(pokemon.name)} name={pokemon.name}/>)
})
}
}
</ul>
</li>
)

Answer

All you need to do is use brackets to allow a multiline function body

const Type = ({onClick, name, onMiniPokemonClick, miniPokemon}) => {
   // some logic   
   return (
      <li
        onClick={onClick}
      >...
      </li>
   )
}

Or if you just need to ensure that miniPokemon is an array when a null/undefined value comes through - you could supply a default argument:

({onClick, name, onMiniPokemonClick, miniPokemon = []})
Comments