Given some data, I was given a challenge to randomly select an image URL from the data.
The call to the API:
export default {
"success": true,
"data": {
"memes": [
{
"id": "61581",
"name": "Put It Somewhere Else Patrick",
"url": "https://i.imgflip.com/1bil.jpg",
"width": 343,
"height": 604,
"box_count": 2
},
{
"id": "285870",
"name": "Squidward",
"url": "https://i.imgflip.com/64ku.jpg",
"width": 500,
"height": 750,
"box_count": 2
},
{
"id": "40945639",
"name": "Dr Evil Laser",
"url": "https://i.imgflip.com/odluv.jpg",
"width": 500,
"height": 405,
"box_count": 2
},
{
"id": "444501",
"name": "Maury Lie Detector",
"url": "https://i.imgflip.com/9iz9.jpg",
"width": 381,
"height": 378,
"box_count": 2
},
{
"id": "1464444",
"name": "Happy Star Congratulations",
"url": "https://i.imgflip.com/vdz0.jpg",
"width": 450,
"height": 292,
"box_count": 4
},
{
"id": "142921050",
"name": "Car Salesman Slaps Roof Of Car",
"url": "https://i.imgflip.com/2d3al6.jpg",
"width": 800,
"height": 450,
"box_count": 2
},
{
"id": "71428573",
"name": "Say it Again, Dexter",
"url": "https://i.imgflip.com/16iyn1.jpg",
"width": 698,
"height": 900,
"box_count": 2
},
{
"id": "100947",
"name": "Matrix Morpheus",
"url": "https://i.imgflip.com/25w3.jpg",
"width": 500,
"height": 303,
"box_count": 2
}
]
}
}
The meme component:
import React from "react"
import memesData from "../memesData.js"
export default function Meme() {
return (
<main>
<div className="form">
<input
type="text"
placeholder="Top text"
className="form--input"
/>
<input
type="text"
placeholder="Bottom text"
className="form--input"
/>
<button
className="form--button"
>
Get a new meme image ๐ผ
</button>
</div>
</main>
)
}
Next, I wrote a function called handleClick() to help select a random URL from the memesData object and passed the function as a value into the onClick event listener. Here's the full code for this small task. So whenever the button is clicked, a random URL is logged to the console.
import React from "react"
import memesData from "../memesData.js"
export default function Meme() {
const memesArray = memesData.data.memes; // get all the meme object and stores them into an array
function handleClick() {
const imagesArray = memesArray.map(meme => meme.url); // gets all the url properties of the meme objects and stores them into an array
let randomUrl = imagesArray[Math.floor(Math.random() * imagesArray.length)];
console.log(randomUrl)
}
return (
<main>
<div className="form">
<input
type="text"
placeholder="Top text"
className="form--input"
/>
<input
type="text"
placeholder="Bottom text"
className="form--input"
/>
<button
onClick={handleClick}
className="form--button"
>
Get a new meme image ๐ผ
</button>
</div>
</main>
)
}
Concepts I learnt
- Event listeners in React
Concepts I revised
- .map() function
NB: this is best viewed on a PC. The code gets scattered on mobile devices.
Thank you Scrimba for the amazing learning platform. You rock! โค
ย