I am trying to display my image after storing in state after I liked the image used a button to display the image

Viewed 27
import { useState } from "react";

function Image({ image }) {
  const [favourite, setFavourite] = useState([]);

  const storeFavourites = () => {
    setFavourite((gif) => [...gif, image]);
    console.log(favourite);
  };

  const viewFavourites = () => {
    favourite.map((url) => {
      <img src={url} />;
    });
  };

  return (
    <div>
      <img src={image} />

      <button onClick={storeFavourites}>Like</button>

      <button onClick={viewFavourites}>View Favourites</button>
    </div>
  );
}

export default Image;

This is a giphy site which generates a random gif when loaded and will generate a different gif based on search results. There is a like button to like the image and it was able to store the image as favourites in a state under const [favourite, setFavourite], however I was unable to display any of the favourite images when I clicked on View Favourites.

1 Answers

Looks like you are returning the view from the function which is not used anywhere inside the component's return function, which is the reason why nothing is rendered.

Here's something what you could do:

  • Store the favourite images in a list.
  • Display the image when a state value is toggled.

So, Here's what you could change:

import { useState } from "react";

function Image({ image }) {
  const [favourite, setFavourite] = useState([]);
  const [showFavourites, setShowFavourites] = useState(false);

  const storeFavourites = () => {
    setFavourite((gif) => [...gif, image]);
    console.log(favourite);
  };

  const viewFavourites = () => {
    setShowFavourites(!showFavourites);
  };

  return (
    <div>
      <img src={image} />

      <button onClick={storeFavourites}>Like</button>

      <button onClick={viewFavourites}>View Favourites</button>

      {showFavourites && favourite.map((url, index) => {
          <img src={url} key={index}
      })}
    </div>
  );
}

export default Image;

If you don't wish to toggle the view but instead just it to change just one time, you could change the viewFavourites to this:

const viewFavourites = () => {
    setShowFavourites(true);
};
Related