Loading
Lesson 03
Courses / Software School Cuts
Changing React.js Box Component Color with a Click While Keeping Track of State with Hook Private

Continuing the example of colored Box components in React.js, the lesson explains how to listen to and handle click events. More specifically the goal is to click a button to change the color of an existing box.

You are introduced to the concept of state using the useState hook to keep track of a color name. See how you assign the return value of the useState hook to two variables created via destructuring of an array. One variable to access the state value and another to mutate (modify) that state value.

When the React state changes, the component renders anew. That is, the function that defines the component is called again and if any values have changed from a previous render, they will be reflected in the updated document object model (DOM) for the web application.

Summary

Controlling Colors in React

Introduction

In this discussion, we explore how to control the background color of a component in React compared to traditional JavaScript methods.

Traditional JavaScript Method

  1. To change an element's color using vanilla JavaScript, you'd typically:
    • Target the element using document.getElementById().
    • Change its style using element.style.backgroundColor.

React Method

React uses a different approach that involves state management for handling dynamic values.

Step-by-Step Guide to Implement Color Change

  1. Adding a Button:

    • Create a button element labeled "Change Color".
    • Use <button type="button"> for the button type.
  2. Handling Click Events:

    • In React, use onClick with a capital 'C'.
    • Pass a function that will be called when the button is clicked.
  3. Defining the Function:

    • The function responsible for changing color is defined inside your main component.
    • Example function: function onChangeColorClick() { ... }.
  4. Using State:

    • Instead of directly manipulating the DOM, React requires the use of state to handle dynamic values.
    • Use the useState hook:
      const [boxColor, setBoxColor] = React.useState('red');
      
    • This creates a state variable boxColor (initially 'red') and a function setBoxColor to update this state.
  5. Changing Color on Button Click:

    • Within the onChangeColorClick function, call setBoxColor('green') to update the state.

Why Use State?

  • Changing the state triggers React to re-render the component, reflecting the updated boxColor in the UI.
  • Direct manipulation of the DOM (like using document.getElementById) doesn’t notify React about changes, which can lead to inconsistencies.

Key Observations

  • Event Handler vs Hook:

    • An event handler (like the click function) is tied to an event (button click).
    • A hook (like useState) is a function that manages state.
  • Reactivity:

    • React reacts to changes in state by re-rendering components, ensuring the interface is always up-to-date with the current state.
  • Destructuring State:

    • When using useState, you can destructure the returned array to easily access the value and setter function.

Additional Notes

  • You can import useState directly for cleaner code:

    import React, { useState } from 'react';
    
  • React's fundamental principle is to "react" to state changes, which helps manage dynamic UI updates efficiently.

By following these steps and principles, you can effectively control component styles and behaviors using state in React.

Video Transcript

Let's say we want to control the color. I want to change the color of the first one using, well, if it's vanilla JavaScript, we'd have to document element by ID, for example, this box to grab it, target it, and then we can change the dot style, dot background color. But that's not really the React way. So the React way is a little bit different. So let's think about that. So I'm going to add here a button. I'm going to say change color for the label. It's basically a button at the top that says change color. Just like HTML, button element, attribute type button, because it's not a submit button. So when I click that, I want something to happen. So it's a click event. Remember from JavaScript, there are events like on click. So we're going to use that. But you know, remember HTML, one way of adding events is like this, right? So pretty much the same way in React, but instead of saying on click all lowercase, the first letter of click has to be capitalized, so the C is capitalized there. And then you have to pass a value here. Remember curly braces after the equals sign. Now this has to be a function. It's similar to JavaScript. In JavaScript, you would say on click, and then some function, and then you call it like that. Here's slightly different. We had the curly braces, and then we got the function name. We don't need the parentheses, because that would call it right away. We don't want it to call it right away. Only on click. So let's say on change color click. Let me call it like that. So I'm going to define this function right before the return within the function. Yeah, that's kind of weird, right? We're defining a function within a function, but that's totally okay. So function space on change color click, parentheses, curly braces like that. Now when I click this button, this function will be called. Now I want this function to change the background color of the first box or what don't matter, yeah, the first box, let's say, to be, let's say green. So how can we do that? Well, usually we would say document, get element by ID or by class or whatever, right? To grab this first box, and then we can do like this example code here. Somehow, if it had an ID here. Let's not be react way. If we do this, you're bypassing react. Remember, react is controlling everything, all the rendering. And if you do this, you're bypassing it. So we won't know when to re-rander or repaint things. So we cannot do it just like that with document get element by ID. So we have to use the state. Yeah, this don't click is called event handler. This function is an event handler. But let me think about this. So we got the color here, right? Now the color is controlled by this value, right? So we need to wait to make that a variable thing. So let's say here's the box color. And that needs to be a variable, but it's a variable that changes. So it's something called state in react. So the way you do it is like this. So we got, oh, we're ready to give you the hands. I hate this out of complete. And anyway, so you can say react.useState and then you give an initial value. In this case, let's say for the box, it is red, okay? I want red to be initial value. And then this call, this is called a hook, okay? Use state as a hook. H-o-k, that's the technical name for this. So basically you're saying, okay, I want to keep track of a certain value. It's like a variable. The initial value is red, a string. And if you want to access this, this whole thing returns two things in an array. Okay, it's an array of two elements. So I want to extract those two things. So I got to use this notation here. So the first one is going to be the value itself and then there's going to be a function. Hold on, let's, so this returns two things, okay? An array, try to explain it. One of the things is the value like this. And the other thing is a function that allows you to change to a new value, okay? Does that make sense? So if I were to access this, I would have to say sub zero for the first element or sub one, but that's not convenient. So I have to use this destructuring notation to extract the first element in an array into this variable and the second element of the array and that other variable. Okay, you can give any name you want. It can be whatever here or whatever there. But by convention, I choose the scripted name here and now as follow with set by whatever the same name I use here to be consistent, okay? So that way now I had access to the box color and I can use it here in line 26. Now whenever I need to change it, that's when I can call this function set box color. So if I click change color button, it calls this function here. Now I want to change the colors. I call set box color, remember this second element from that array with whatever value I want, green. So if I do that, save it and click change color. Now it's changed. Now let me read your questions. A hook is not an event listener, okay? Event listener is a function tied to an event. And for example, the button has a non-click. So we have this function here. This function because it's tied to the on click of the button could be called an event handler function, okay? Now hook is just the name of this thing use state, okay? If you want to read more about it go on the React website. But all it does is, okay, you want to keep track of some value, right? That can be changed over time in our application. The way you use it, you call this function called use state, give us an initial value for this variable, right? State variable. In this case it's going to be the string red. So you can access the value from the return value of use state. That's an array of two things. Don't ask me why they wrote it this way. That's the way that people who wrote React did. I know it's a bit weird, but just the way they did it. It's simply an array that returns the first element being the value like red in this case. And the second being the function that allows you to change that value to a new one, okay? That's why we always do this. So I use this destructuring notation from JavaScript to extract the first element of the array into this variable called box color. And then the second element of the array into this function, this called set box color. That's an variable, you can think of that in a variable as well. Anyway, I know it's a little bit weird, but I think you can just take it for granted now and keep going, maybe down the road you better understand. Okay. Yeah, so Carlos asks a good question. Every time state changes, the component is re-rendered. That's why I told you before we cannot just do document, get element, buy ID, and then set the style background color because you're kind of doing it around react and react won't know that you changed it. So the reason we use state is that every time we change the state, any variable in the state, react will re-render the component, meaning it will repaint it, right? So when I say, if I want to refresh this, I click refresh to reset everything. When I click change color, what happens is it calls the function on change color, I click that in turn, it calls the function to change the value of the state for the box color. So because it changes to a new value, the state has changed. When the state changes, the function app gets called again. Therefore, this template is called again. Now the value of box color will be green, right? Because we changed it. And then at line 26, color will be green here. That's why it changed it automatically. So react reacted to it. So as I was saying, the name of react is react, right? It's reacting to something. And every time the state changes, it reacts to it. Okay, the state changed. We've got to re-render everything because things might look different. Somebody commented this card can have over 300 people. That's probably with the nitro subscription, no? Okay, somebody asked, did it import useState up top or is it convention out to have it like react useState? Yeah, so that's a good question. So useState is available through the react object that we import at the top. But you're actually gonna see a lot of people using simply useState without reference to react dot. And that's totally fine. How can you use that? Well, in the top, you have to add a comma and then curly braces to take the useState from whatever this export is, okay? So that way you can use it in isolation. That's totally fine as well. Does that make sense? I prefer to have it this way because we're beginning, so you understand where it comes from. Oh, okay, it comes from react, you know? But you can totally do the other way as well. It's shorter. Okay, so everybody understand now that's why it's called react. Every time the state changes, it re-renders the component. Everybody that's in here will get re-rendered. The app itself gets re-rendered. At that in turn, re-renders the box. So everything gets a new look, fresh paint atop. And that's why you box color now when I click that will become green because the new valid box color became green and then I call this again with that value. Okay, so every time you need to keep track of something, you use state. Okay, think of it like in normal programming, you wanna store something and change it later, possibly. You make a variable, right? It's kind of like that except you have to use the react state so that it knows that you're changing it so it can react according.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? 😆👍
Consider a donation to support our work: