Animal Fun Facts

I seem to have gotten stuck when I get to the click event portion of this tutorial. I followed along with the video and have rechecked my work several times. Background and images are displaying fine, however, when I click on the animal images I’m not seeing the random funFacts. When I check the console it says that const funFact is not defined. …but it is defined inside the function! I hope someone can tell me what I’m missing. Below is some of my code.

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 = []; for ( const animal in animals) { images.push( <img key={animal} className = 'animal' alt = {animal} src = {animals[animal].image} ariaLabel = {animal} role = 'button' onClick = {displayFact} /> ) }; function displayFact(e) { const selectedAnimal = e.target.alt const animalInfo = animals[selectedAnimal]; const optionIndex = Math.floor(Math.random() * animalInfo.facts.length); const funFact = animalInfo.facts[optionIndex]; document.getElementById('fact').innerHTML = funfact; } const animalFacts = ( <div> <h1>{title == "" ? "Click an animal for a fun fact" : title}</h1> {background} <p id='fact'></p> <div className = 'animals'> {images} </div> </div> ); ReactDOM.render(animalFacts, document.getElementById('root'));

Hi everything seems to be correct exept that I found a few typo mistakes in on of your functions :

function displayFact(e) {
  const selectedAnimal = e.target.alt;
  const animalInfo = animals[selectedAnimal];
  const optionIndex = Math.floor(Math.random() * animalInfo.facts.length); 
  const funFact = animalInfo.facts[optionIndex];
  document.getElementById('fact').innerHTML = funFact;
}

So you missed a column after you selectedAnimal variable, and on the last line in your displayFact(e) function you wrote " = funfact;" which is supposed to be written as funFact;

But overall you did good !

1 Like

Good catch. Thanks Chris!

1 Like

No worries. :slightly_smiling_face:
Happy coding !

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.