Animal Facts Challenge Project

Okay, so I officially have no idea why my code isn’t working.
My background image, h1, and the images of the animals are coming up, however the animal facts are not popping up. I don’t know where my error is.
I’d appreciate any help and explanations! :slight_smile:

Thank you in advance

Here is the full code from Animal Facts Project

//Translation Services
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 = (
ocean
);
function displayFact(e) {
const animal = e.target.alt;
const index = Math.floor(Math.random() * animals[animal].fact.length);
const funFact = animals[animal].fact[index];
const p = document.getElementById(“fact”);
p.innerHTML = funFact;
}
const images = ;
for (const animal in animals) {
const image = (

);
images.push(image);
}
const animalFacts = (

{title === "" ? "Click an animal for a fun fact" : title}

{background}

{images}
);

root.render(animalFacts);

Please format your code. With an image tag already interpreted, this is not debuggable.
See How to format code in posts for reference

1 Like
//Translation Services
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" />
);
function displayFact(e) {
  const animal = e.target.alt;
  const index = Math.floor(Math.random() * animals[animal].fact.length);
  const funFact = animals[animal].fact[index];
  const p = document.getElementById("fact");
  p.innerHTML = funFact;
}
const images = [];
for (const animal in animals) {
  const image = (
    <img
      onClick={displayFact}
      key={animal}
      className="animal"
      src={animals[animal].image}
      aria-label={animal}
      role="button"
    />
  );
  images.push(image);
}
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);

sorry about that

2 Likes

There is no alt tag on your images, so e.target.alt is undefined.

2 Likes
<img
      onClick={displayFact}
      key={animal}
      className="animal"
      alt={animal}
      src={animals[animal].image}
      aria-label={animal}
      role="button"
    />

I added alt in, the facts still aren’t coming up.

FIXED***

I needed to change

 const index = Math.floor(Math.random() * animals[animal].fact.length) 

to

 const index = Math.floor(Math.random() * animals[animal].facts.length)

Thanks for sharing, it’ll be helpful