Animal Facts React Help

Hello, I am having some trouble while completing the animal facts react project, the project works up until the displayFact function as the fact does not seem to appear when the image is clicked. Thank you in advance for any help!

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

const container = document.getElementById('app');
const root = createRoot(container);

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 animalName = e.target.alt;
const optionIndex = Math.floor(Math.random() * animalName.facts.length);
const funFact = animalName[optionIndex];
document.getElementById('fact').innerHTML= funFact;
}


const title = ''
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>
);

root.render(animalFacts);

The problem lies in the following two lines:

const optionIndex = Math.floor(Math.random() * animalName.facts.length);
const funFact = animalName[optionIndex];

To the animalName variable , you assigned e.target.alt which is a string.

So animalName.facts.length won’t work.

Instead you should do something like:

const optionIndex = Math.floor(Math.random() * animals[animalName].facts.length);
// or 
const optionIndex = Math.floor(Math.random() * animals[animalName]['facts'].length);
// Both will work

Similarly, for funFact, you can do something like:

const funFact = animals[animalName].facts[optionIndex];
// or
const funFact = animals[animalName]['facts'][optionIndex];
1 Like

Thank you so much! This now works great!

1 Like