Animal Fun Facts - problem with arrow function

Hi! :wave: I’ve been working on the Animal Fun Facts exercise this afternoon, and I’ve just finished. However, I did have an issue when I tried to use an arrow function for the displayFact function…

With a regular function statement, my code is as follows:

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

const background = <img className="background" alt="ocean" src="/images/ocean.jpg" />
const title = '';
const images = [];
const showBackground = false;

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

function displayFact(e) {
  const animalInfo = animals[e.target.alt];
  const randomFactIndex = Math.floor(Math.random() * animalInfo.facts.length);
  const randomFact = animalInfo.facts[randomFactIndex];
  document.querySelector('#fact').innerHTML = randomFact;
}

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

ReactDOM.render(animalFacts, document.querySelector('#root'));

So, note the displayFact function. If I write it as an arrow function, like so…

const displayFact = e => {
  const animalInfo = animals[e.target.alt];
  const randomFactIndex = Math.floor(Math.random() * animalInfo.facts.length);
  const randomFact = animalInfo.facts[randomFactIndex];
  document.querySelector('#fact').innerHTML = randomFact;
}

… the click event no longer works!

Why doesn’t this work?! Have I forgotten something fundamental about arrow functions, or is there some React factor at work I don’t know about? Something with this?

Hello,

If you had both functions in the same spot in your code, then the issue was likely because of hoisting.

You can use a function declared with function name(parameter) anywhere in the file because of hoisting, but when you assign an arrow function to a const, you can only use it after it’s been defined.

Try moving your arrow function to before you use it in the for loop.

1 Like

Ah, that’s it! Of course… thanks, @selectall. I had forgotten something fundamental about arrow functions!