React | Animal Fun Facts | onClick Event

Hello All,

I was going thru the Animal Fun facts (https://www.codecademy.com/courses/react-101/projects/js-react-animal-fun-facts) and not sure I am understanding HOW I am able to get a particular piece of information.

Below is the section I am talking about and represents the state of the project at the end of step 11:

for (const animal in animals) {
  images.push(<img key={animal}
    className="animal"
    alt={animal}
    src={animals[animal].image}
    aria-label={animal}
    role="button"
    onClick={displayFact}
  />)
}

function displayFact(e) {
  console.log(animals)
  let animalName = e.target.alt
  const animalInfo = animals[animalName]
  const optionIndex = Math.floor(Math.random() * animalInfo.facts.length);

  const funFact = animalInfo.facts[optionIndex]
  document.getElementById("fact").innerHTML = funFact
}

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.

Hi,
the variable ‘animals’ (containing an object) is provided to you by Codecademy.
It is imported and therefore available at the top of the file:

import { animals } from './animals.js';

In the tabs you see the file animals.js that is exporting ‘animals’.
Does that answer your question?

Hey @ mirja_t,

OMG… cannot believe I missed that. I was so focused on the loop, totally missed where IT was getting animals.

Thanks so much :slight_smile:

1 Like