2

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
Paul
  • 25
  • 4

1 Answers1

1

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
DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
  • 1
    Thanks so much for all the help. It's working great now. All of the extra tips are very appreciated. – Paul Jun 07 '21 at 16:52