skip to Main Content

I’m trying to pass a state variable called ‘imageSize’ into a map render object, but I can’t figure out how to do this, I have 2 state variables:

const [searchImages, setSearchImages] = useState([]);    
const [imageSize, setImageSize] = useState("regular");

I currently have mapped over searchImages with no problems, but when I try to add ‘imageSize’ into my img src , it doesn’t work, like so:

    {searchImages.map(item => (
           <img className='image-item' key={item.id} src={item.urls.imageSize} alt='cool'/>
    ))}

Could you provide advice on how I can achieve this.

2

Answers


  1. You are using imageSize as a state to trigger different image size in the object item -> urls, therefore you can not use dot notation, but you need bracket notation as:

    {searchImages.map(item => (
      <img className='image-item' key={item.id} src={item.urls[`${imageSize}`]} alt='cool'/>
    ))}
    
    Login or Signup to reply.
  2. You are trying to combine both states into one, which is not required. As you are using searchImages as an array of items and you need the imageSize to be used as size for the image, you can try doing this:

    {searchImages.map(item => (
        <img className='image-item' key={item.id} src={`${item.urls}${imageSize}`} alt='cool'/>
    ))}

    If you want to add any "-" or "/" as a combination for both the variables you can do something like this {`${item.urls}-${imageSize}`} or {`${item.urls}/${imageSize}`}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search