DEV Community

Bo Louie
Bo Louie

Posted on

A closure challenge

This closure challenge was featured in The Complete JavaScript Course 2023 by Jonas Schmedtmann on Udemy.

Challenge

Take the following IIFE provided and at the end of the function, attach an event listener that changes the color of the selected h1 element ('header') to blue, each time the body element is clicked. Do not select the h1 element again! And then explain why this worked, as if to a 5 year old. Use analogies if possible.

Solution

(function(){
    const header = document.querySelector('h1');
    header.style.color = 'red';
    document.body.addEventListener('click', function() {
        header.style.color = 'blue';
    });
})();
Enter fullscreen mode Exit fullscreen mode

This code makes the header text turn red when the page loads, and blue every time you click on any part of the body. Give this a try at codepen.

Think of it like having a big red crayon and a blue crayon. When the page starts, you color the header with the red crayon. Then, you tell the computer that every time you click on the body, you want to color the header with the blue crayon. So every time you click, the header changes color from red to blue, just like using different crayons.

React

Can you show an example of the same scenario using React?

import React, { useState } from 'react';

const Header = () => {
  const [headerColor, setHeaderColor] = useState('red');

  const handleBodyClick = () => {
    setHeaderColor('blue');
  };

  return (
    <>
      <h1 style={{ color: headerColor }}>Header</h1>
      <body onClick={handleBodyClick} />
    </>
  );
};

export default Header;
Enter fullscreen mode Exit fullscreen mode

This code uses the useState hook from React to keep track of the color of the header text. Initially, the color is set to red. The body is given an onClick handler, handleBodyClick, which updates the color of the header text to blue every time it is clicked.

In React, hooks are functions that let you "hook into" React state and lifecycle features from your functional components.

Think of hooks as special tools that you can use in your components to add extra functionality and interact with React. They let you reuse stateful logic and change the behavior of your components without having to write a class component.

In the example I provided, useState is being used to manage the color of the header text. The useState hook returns an array with two values: the current state and a function to update the state. The header color is stored in the state, and the function to update it is used in the handleBodyClick handler to change the header color to blue every time the body is clicked.

There are several built-in hooks in React, such as useState and useEffect, that you can use to add state management, handle side effects, and control how your component renders. You can also write your own custom hooks to reuse logic across your components.

Thanks for reading!

Top comments (0)