Animal Fun Facts onClick not working

I am stuck in the mud on this React project. I can get all the images to display, but for the life of me I can’t get the text to display when I click on an image. I would appreciate any help you may give.

Here is a link to the project.

Here is a gist of all the project code.

And here is my JS so far:

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

const container = document.getElementById('app');
const root = createRoot(container);
const title = '';
const background = <img className='background' alt='ocean' src='/images/ocean.jpg' />;

// display facts about each animal onClick
const displayFact = (event) => {
  const selectedAnimal = event.animal.alt;
  const animalInfo = animals[selectedAnimal];
  const randomIndex = Math.floor(Math.random() * selectedAnimal.facts.length);
  const animalFacts = animalInfo.facts[randomIndex];
  document.getElementById('fact').innerHTML = animalFacts;
}

// setting images in foreground
const images = []
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}
    />
  );
}

// display clickable animal images
const animalFacts = (
        <div>
          {background}
          <h1>{title === '' ? 'Click an animal for a fun fact' : title}</h1>
          <div className='animals'>
            {images}
            <p id='fact'></p>
          </div>
        </div>
      );

root.render(animalFacts);
const selectedAnimal = event.animal.alt;

Does the event have an animal property? Or is it supposed to be event.target.alt ?

1 Like

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