Search code examples
javascriptnode.jsreactjscreate-react-app

React ternary operator used to iterate through a results array (otherwise undefined), is there a different, preferred approach?


I'm new to React and my current code works, but is there a better, "React way" (w/o ternary) of mapping through an empty array, before it has the results (without returning undefined)?

I'm rendering a materialize card for every result returned from an API search. What the code does isn't the issue because it works w/ my current solution.

Thanks in advance.

class NutritonixResultsDisplay extends Component {

render() {
    const hits = this.props.nutritionixResults.hits;
    return (
        <div className='nutritionixResultsDiv'>
            {hits
                ? hits.map((result, i) => (

                    <div key={i} className='nutritionixResultDiv'>
                        <Card className='cardDisplay' header={<CardTitle reveal  image='' waves='light'/>}
                            title={result.fields.item_name}reveal={<div><p>{`Calories: ${result.fields.nf_calories}`}</p><p>{`Protein: ${result.fields.nf_protein}`}</p></div>}> <p><a href="/">This is a link</a></p>
                            <p>{`Brand Name: ${result.fields.brand_name}`}</p>

                        </Card>
                    </div>

                ))
                : ''}
        </div>
    );
}
}
export default NutritonixResultsDisplay;

Solution

  • Just simply make hits an empty array.

    const hits = this.props.nutritionixResults.hits || [];