Trouble with React animal facts project

I’m having trouble solving the react Animal-Fun-Facts project I’m up to part 9-10 And I cant understand the console gives Me an error that .length in line 7 is called on an unknown variable
Https://www.codecademy.com/courses/react-101/projects/js-react-animal-fun-facts

import { animals } from './animals';
import React from 'react';
import ReactDOM from 'react-dom';

const images = [];
function displayFact(e) {
  const randomAnimal = Math.floor(Math.random() * e.facts.length);
  document.getElementById('fact').innerHTML = randomAnimal; 
};
for (const animal in animals) {
  images.push(<img onClick={displayFact(animal)} key={animal} className='animal' alt={animal} src={animals[animal].image} aria-label={animal} role='button'  />
  )
};

const background = (
  <img
    className='background' 
    alt='ocean' 
    src='/images/ocean.jpg' />
);
const title = "";
const animalFacts = (
  <div>
    <h1>{title === "" ? "Click an animal for a fun fact" : title}</h1>
    {background}
    <div className='animals'>
      {images}
    </div>
    <p id='fact'></p>
  </div>
)
ReactDOM.render(
  animalFacts,
  document.getElementById('root')
)

Hi there.

You’re getting that error because the way you’ve implemented the event handler and assigned it to the three images is a little off.

What you’re doing here:

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

is calling displayFact(animal) for each animal in the array and assigning it’s return value to the onClick attribute. What you’re meant to do is assign the function, which you do by simply typing the name of the function without the parentheses (and associated parameters).

As a result, when you’re calling the function at this stage, e has a value of dolphin - as that’s the first animal in the animals object. However, I should point out that this value is the string dolphin, and not the nested dolphin object from the animals object. The string object does not have a property of facts, so you’re effectively trying to do this:

"dolphin".facts.length

If you recall, event handlers get passed an implicit parameter by the JavaScript engine when they are called, which is an Event object. This is what is supposed to be the value of e. From this, you can compute the element that was clicked by looking at Event.target.

Once you have the target of the event, you can then use that information to get the animal that was clicked, and pull a random fact about it. :slight_smile:

Hope that helps. :slight_smile:

1 Like

That worked! Thanks So Much!

1 Like