Animal Fun Fact -React Objective

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

why cant I use className for paragraph instead of id;

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

when I use className instead of id, this function in app.js does not work, why ?

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

Hello, and welcome to the forums!

You can’t change it from id to className because:

  1. document.getElementById() (MDN Docs) looks for an element with a specified id. Removing the id from the paragraph element means that it can’t find it anymore with the code provided.

  2. If you do fix the previous issue by changing the code to find the element by the className instead, you’ll still have an issue with how it looks. The CSS in styles.css is using a selector based on fact being an id - it’s using #fact as the selector.

thx for the reply, I thought className refer to id in a way. (I just didn’t know enough about the selectors)
But I get it now. It just refers to class but has to be written as className in React.
A class and id are different things, and as the selector looks for id, there is no point in using className.

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