Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass a state variable into render object in React

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'/>
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading