Animal Fun Facts solution

Hello, here’s the finished code for the Animal Fun Facts project in the Learn React course. The hints and YouTube video weren’t really much use, and neither was a friend who earns a ton of money writing writing JavaScript for a well-known search engine hehe. Turns out that a lot of this code is not best practice at all, but can only assume Codecademy wants us to learn a certain way… It took me a long time to figure out the solution so thought I’d post it here.

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 title = "";
const images = [];

function displayFact(e) {
  const animal = e.target.alt;
  const index = Math.floor(Math.random() * animals[animal].facts.length);
  const funFact = animals[animal].facts[index];

  const p = document.getElementById("fact");
  p.innerHTML = funFact;
}

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

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);
1 Like