Animal Fun Facts - toggle - extra credit

I am on the last exercise, and try to create a button: show / hide background image.

I made a function switchBackground():

  • upon clicking the button alert displays properly :slight_smile:
  • showBackground remains true and I don’t know how to make it false :frowning:

I did console.log(showBackground) within the function and seems that it updates variable.
However, outside of the function showBackground is always true…

I guess it is scope-related, but not sure how to make all things work properly.
Would really appreciate your help!

My code below:

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

const title = "";
const background = <img className="background" alt="ocean" src="/images/ocean.jpg" />;

const images = [];
for (const animal in animals) {

function displayFact(e) {
  const selectedAnimal =;
  const randomNumber = Math.floor(Math.random() * animals[selectedAnimal].facts.length);

  const funFact = animals[selectedAnimal].facts[randomNumber];
  document.getElementById("fact").innerHTML = funFact;

let showBackground = true;

function switchBackground() {
    showBackground = !showBackground;

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

ReactDOM.render(animalFacts, document.getElementById("root"));

Hello, and welcome back to the forums.

Changing the value of the that boolean doesn’t trigger React to re-render after it’s already been rendered. The extra challenge at the end of the project was talking about you manually changing the value of showBackground so you can see the output change after you press the Save button again.

You implemented that correctly in the JSX with your {showBackground && background} line, which was the purpose of the challenge. You’ll learn in future exercises how to use variables in a similar way to have the component re-render. Be on the lookout for exercises about state and props.

1 Like

Thank you!

So seems that I tried to introduce something ahead of the future lesson.
Will try to tackle the topic again once I get to state & props.

1 Like

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