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
You are using
imageSize
as a state to trigger different image size in the objectitem -> urls
, therefore you can not use dot notation, but you need bracket notation as: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 theimageSize
to be used as size for the image, you can try doing this: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}`}