Jonathan
Jonathan

Reputation: 469

How to do statement in a statement in react?

I need to do a statement and print if the array is not empty, and if it's empty print an error message.

    {isEmpty(this.props.items) ? errorMessage : working}

The simple idea is to replace working to:

{this.props.items && this.props.items.map((movie) => (
    <Link to={`/movie/${movie.id}`} key={movie.id}>
        <img className="Image-movie"
           src={`https://image.tmdb.org/t/p/w500/${movie.poster_path}`} 
           alt={`${movie.title}`}/>
    </Link>
))}

I try it to insert it but tells something about code syntax, any idea?

Upvotes: 1

Views: 52

Answers (4)

Dr. Selva Mary G
Dr. Selva Mary G

Reputation: 688

{this.props.items.length>0? this.props.items.map((movie) => (
<Link to={`/movie/${movie.id}`} key={movie.id}>
    <img className="Image-movie"
       src={sourcePath} 
       alt={movie.title}/>
</Link>)): errorMessage}

Upvotes: 0

Mustafa Alfar
Mustafa Alfar

Reputation: 185

I think you can do that,

const {items} = this.props;
{items.length > 0  ? items.map((movie) => (
    <Link to={`/movie/${movie.id}`} key={movie.id}>
        <img className="Image-movie"
           src={`https://image.tmdb.org/t/p/w500/${movie.poster_path}`} 
           alt={`${movie.title}`}/>
    </Link>
)): (<Spinner /> || null) }

Upvotes: 1

Dupocas
Dupocas

Reputation: 21317

One of many solutions is to asign the second statement to a const

const items = this.props.items ? this.props.items.map((movie) => (
    <Link to={`/movie/${movie.id}`} key={movie.id}>
        <img className="Image-movie"
           src={`https://image.tmdb.org/t/p/w500/${movie.poster_path}`} 
           alt={`${movie.title}`}/>
    </Link>
)) : null

return {isEmpty(this.props.items) ? errorMessage : items}

Since the first check is not necessary you could just do

return !this.props.items.length ? error : this.props.items.map(/*...*/)

Upvotes: 1

adel
adel

Reputation: 3507

why you are checking again for props.items:

 const renderItems = this.props.items.map((movie) => (
        <Link to={`/movie/${movie.id}`} key={movie.id}>
            <img className="Image-movie"
               src={`https://image.tmdb.org/t/p/w500/${movie.poster_path}`} 
               alt={`${movie.title}`}/>
        </Link>
    ))



 {isEmpty(this.props.items) ? errorMessage : renderItems}

Upvotes: 0

Related Questions