Within displayFact() I am doing the following: const animalInfo = animals[animalName]
But how am I able to access animals?
Is it because the onClick's event is allowing that? If so, would that be analogous as to how the src is accessing animals and/or aria-label is getting animal? As you can see I logged out animals and the info is there… but just a bit of a mind twist going on here. Any walk thru help is appreciated.
Good day all, can anyone look at my code and let me know why my onClick is working please. I believe I have done everything as per the tutorial… I’ve searched for typos but nothing. Would appreciate the guidance, thank you.
import { animals } from './animals';
import React from 'react';
import ReactDOM from 'react-dom';
const title = "" ;
const background = (<img className="background" alt= "ocean" src= "/images/ocean.jpg" />);
const images= [];
function displayFact(e) {
const selectedAnimal = e.target.alt ;
const animalInfo = animals[selectedAnimal];
const optionIndex = Math.floor(Math.random() * selectedAnimal.facts.length);
const funFact = animalInfo.facts[optionIndex];
document.getElementById("fact").innerHTML = funFact;
}
for (const animal in animals)
{ images.push(
<img
key = {animal}
className = 'animal'
src={animals[animal].image}
alt={animal}
aria-label= {animal}
role= 'button'
onClick= {displayFact}
/>
)
}
const animalFacts = (
<div>
<h1>{title ? title : 'Click an animal for a fun fact'}</h1>
{background}
<div className= "animals"> {images}</div>
<p id="fact"></p>
</div>) ;
ReactDOM.render(animalFacts, document.getElementById("root"));
animalInfo is an object and does have a facts property (you can look at the animals.js file to see the structure of animals by clicking the folder icon).