Reputation: 21
import React from "react";
import memeData from "./memeData";
export default function Meme(){
const [memeImage, setMemeImage] = React.useState("")
function getMemeImage(){
const memesArray = memeData.data.memes
const randomNumber = Math.floor(Math.random() * memesArray.length)
setMemeImage(memesArray[randomNumber].url)
}
return(
<div>
<form className="form">
<input type="text" className="form-input" placeholder="Top Text" />
<input type="text" className="form-input" placeholder="Bottom Text" />
<button className="btn" onClick={getMemeImage}>Get a new meme image 🖼</button>
</form>
<img src={memeImage} alt="memes"></img>
</div>
)
}
So when i click the button it should add new image but it just return an empty string and the icon of img when it isnt working
Upvotes: 1
Views: 27
Reputation: 41893
The data you provided looks fine. I believe the problem you are facing is auto-refreshing website with every button click, because your button is wrapped with form
. The default button type is submit
, that's why you are not able to display the image. Simply change it's type to button
.
<button type="button" className="btn" onClick={getMemeImage}>Random img</button>
Upvotes: 1