Paul
Paul

Reputation: 25

Can I use a ternary operator inside of an image tag?

I'm trying to use a ternary operator inside an image tag to toggle between two sets of gifs. It isn't working. Is my syntax messed up, or can I just not do this? Any suggestions? (code below)

import React, { useState } from 'react'

const Artist = ({currentArtist}) => {
    const ghostify = () => {
       if(isGhost) {
            setIsGhost(!isGhost)
        } 
    }

    //state
    const [isGhost, setIsGhost] = useState(false)

    return (
        <div className="artist">
            <img src={isGhost ? currentArtist.vid : currentArtist.ghostVid} alt= 
                {currentArtist.name} />
            <h2>{currentArtist.name}</h2>
            <h3>{currentArtist.title}</h3>
            <button onClick={ghostify()}>Ghostify</button>
        </div>
    )
}

export default Artist

Upvotes: 2

Views: 1677

Answers (1)

GʀᴜᴍᴘʏCᴀᴛ
GʀᴜᴍᴘʏCᴀᴛ

Reputation: 8920

Going by off what I'm seeing because there is no error in your question and per memory the onClick:

<button onClick={ghostify()}>Ghostify</button>

will always fire (Learned from "React onClick function fires on render") so it should be:

<button onClick={() => ghostify}>Ghostify</button>

A couple of suggestions. I always prefer to declare my useState and useEffect and I want to say that I read it was advised.

I dont think you need to check the condition of the function so:

const ghostify = () => {
    if(isGhost) {
        setIsGhost(!isGhost)
    } 
}

would be:

const ghostify = () => setIsGhost(!isGhost)

I prefer to de-structure and when you dont always know if you'll have a name or title I like to set a default value or condition the render. I'd change your component to condition for name and title:

import React, { useState } from 'react'

const Artist = ({ currentArtist }) => {
  const [isGhost, setIsGhost] = useState(false)
  const ghostify = () => setIsGhost(!isGhost)
  const { vid, ghostVid, name, title } = currentArtist

  return (
    <div className='artist'>
      <img src={isGhost ? vid : ghostVid} alt={name} />
      {name && <h2>{name}</h2>}
      {title && <h3>{title}</h3>}
      <button onClick={() => ghostify}>Ghostify</button>
    </div>
  )
}

export default Artist

Upvotes: 1

Related Questions