Animal Facts Exercise - Animal facts not displaying on click - 'Cannot set properties of null (setting 'innerHTML')


I am close to completing the React exercise of displaying the animal facts. However, the onClick isn’t working. After a long time trying to understand what the error is, I dived into the console and I got the error 'Cannot set properties of null (setting ‘InnerHTML’). I don’t understand what I need to change. Here is my code…

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'/>; 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} /> ) }; 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> ); function displayFact(e) { const fact = animals[].facts; const randomNum = Math.floor(Math.random() * fact.length); const facts = fact[randomNum]; document.getElementById('fact').innerHTML = facts; } root.render(animalFacts);

Any help will be much appreciated. Thanks :slight_smile:

Looks like you’re setting the class name to ‘fact’ but trying to access the element with id of ‘fact’


Thank you very much!

1 Like