02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School

Components that change with state

Understanding Components that Change with State

In this lecture, we explored the concept of state in React, diving into how it enables components to handle dynamic behavior. State complements props by allowing components to track and react to changes internally.


Key Takeaways

1. State vs. Props

  • Props: Data passed into a component, generally immutable from the component's perspective.
  • State: Managed within the component and expected to change over time.

Implementing State

We modified the PortfolioItem component to introduce state. The process included:

a. Adding a Constructor

The constructor was defined using ES6 class syntax:

constructor(props) {
    super(props);
    this.state = {
        hasImage: true, // Initial state
    };
}
  • super(props): Ensures the parent class (React.Component) receives the props.
  • State initialization: Defines the initial value for hasImage.

b. Using State in the Render Function

To conditionally render the component based on the state:

{this.state.hasImage ? (
    <img src={this.props.imgPath} alt="Portfolio Item" />
) : null}
  • Ternary Operator: Conditionally checks hasImage. If true, the image is displayed; otherwise, null is returned.

c. Handling Events to Update State

An onClick handler was added to toggle the visibility of the image:

onUpdateImageState = () => {
    this.setState({ hasImage: !this.state.hasImage });
};
  • setState: Updates the state and triggers a re-render.
  • Bound Methods: Used ES6 arrow functions to ensure this remains scoped to the component.

Example of the Updated Component

Here’s the full updated code for the PortfolioItem:

import React from 'react';

class PortfolioItem extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hasImage: true,
        };
        this.onUpdateImageState = this.onUpdateImageState.bind(this);
    }

    onUpdateImageState() {
        this.setState({ hasImage: !this.state.hasImage });
    }

    render() {
        return (
            <div onClick={this.onUpdateImageState}>
                {this.state.hasImage ? (
                    <img src={this.props.imgPath} alt="Portfolio Item" />
                ) : null}
            </div>
        );
    }
}

export default PortfolioItem;

Highlights of ES6 Features

  • Class Constructors: Simplified the instantiation of components and passing props to parent classes.
  • Arrow Functions: Ensured proper scoping of this in methods.
  • Conditional Rendering: Used the ternary operator for concise logic.

Testing State Changes

The application was tested to ensure that:

  1. The image disappears on click when hasImage is toggled to false.
  2. The image reappears when toggled back to true.

Recap

This lecture emphasized the difference between props and state, showcasing how state allows components to handle internal changes. By integrating dynamic behavior, React components become more interactive and responsive.

In the next lecture, we'll expand on these concepts, introducing arrow functions and further exploring ES6 features to streamline React development.

Video Transcript

00:00In the last few lectures,
00:02we've been exploring different types of props
00:05and now it's time for us to explore a state
00:07and really understand the difference
00:09between a property and a state.
00:11And as I've mentioned before, a property is something
00:13that we assume the component doesn't need
00:15to know that it will change.
00:17Properties could change as well,
00:19but not initiated by the component
00:22on Contrera state is something inside of a component
00:26that we expect to change.
00:27But not only do we expect it to change,
00:29we expect our component to be aware
00:31that it's going to change.
00:33Most of the time we want everything to be props,
00:36unless it's something that we need our component to be aware
00:40of that is going to change.
00:41We're gonna see it in action right away.
00:43Let's really jump into it
00:45and let's learn how to announce these different states
00:48and how to basically use them in react.
00:52We are diving deeper and deeper into the world of react
00:55and we already met props and even props children.
00:59The next item that we wanna meet is state.
01:02And we're gonna take a very deep look at the differences
01:04between them in the next lecture.
01:06But I want us to start off from jumping right inside
01:08and seeing state in action so we could then compare
01:11and contrast between what a prop is and what a state is.
01:16So to do that, I'm gonna go into my code
01:18and into my portfolio item.
01:19I'm gonna add another function this time.
01:22It's not just a regular function,
01:23but it's gonna be our constructor, which is a, uh,
01:27as you guessed it, construct.
01:29Let me just make sure I cons,
01:33which is an ES six way to define classes in JavaScript.
01:37If you work with prototypes, it is the constructor similar
01:40to the constructor in prototype,
01:42which basically is the instantiate of the class.
01:45This is automatically called
01:47whenever the class is instantiated.
01:49Now the react component already expects the props property
01:53as you, we've been working with it already props
01:56and it's in the, it's in the built in that
01:58that's what it's expecting.
01:59Now, if we just created the constructor,
02:02it automatically overrides the constructor of react.
02:05And what we really wanna do is we wanna send over
02:07to that component.
02:09We wanna send the props.
02:10So to do that I'm gonna call the super function,
02:13which basically does exactly that.
02:15It basically calls the parent constructor
02:18and sends it into, into its construct, whatever we want.
02:21In this case, we're just gonna pass through the properties
02:24that are being sent into our portfolio.
02:27Next but not next item. After we set, we called our su.
02:30Not super, but super.
02:32Once we've sent that in, it's time for us
02:34to start talking about state.
02:36'cause we had to recreate the initial state
02:38and now we need a, the initial state
02:40of our props and our constructor.
02:42Now we want to create the initial state of our state.
02:45Now the basic concept of state,
02:46and I'm just gonna set it as a variable
02:49and I'm gonna go ahead here and set has it has image.
02:52And this is gonna be basically a property
02:54that is gonna define if our our element has an image or not.
02:59Is this image available or not? Within the component?
03:01Really in our case, it's gonna make it invisible
03:03'cause that's really the only visible content inside
03:06of all this, all this, everything
03:08that's going on inside of here.
03:09But literally what I want to do is I want
03:13to basically I create that initial state
03:15and that initial state is basically saying
03:18to the application is that we wanna watch for this.
03:21Whenever this changes,
03:23that means something visual has changed as well
03:25or it should reflect visual changes Contrary to props,
03:29we are, they're constant, they don't change.
03:31So once we've pushed them into an application,
03:34a property is never going to change.
03:36You would never go into a property and go into that property
03:39and just set its value to be something else.
03:42You would never do that. Once a property is set,
03:44it's in the the class, that's it.
03:46It's assumed to be a constant.
03:48The same is true by the way
03:50that you would never go into a state
03:51and change it through has image.
03:53You wouldn't just go and just set it to be false or true.
03:56And the reason is very simple
03:57because if I do it this way, react doesn't know
04:00that it changed or at least it doesn't go
04:03through the normal flow that it needs to.
04:04So I would never change it this way.
04:07We're gonna see how we change it in a second.
04:08But before we look into changing, let's go ahead
04:11and use, this has image inside of our rendering function.
04:16And really what we wanna do is we want this code to be
04:19or displayed or not based on if the value here equals true.
04:23Now, to do that, I'm gonna wrap
04:24around this area in those curly brackets again to indicate
04:27to JSX that we're gonna be putting here a variable.
04:30But in this case we're gonna put in a ary operator
04:33and the terrain operator,
04:35which is basically a condensed if statement
04:37is going to go this way.
04:38I'm gonna say this, do state do has image.
04:42That is basically our first line.
04:44This could be true or false.
04:46And I'm gonna set a question mark basically asking,
04:48is this value equals to true or any value?
04:52By the way, it could be 10, uh, it could be a string.
04:54Does this have a value?
04:56If it's zero, if it's false, if it's null,
04:59then all that would be false.
05:01But in this case, because it's set to true,
05:02then this will be triggered.
05:04Now we wanna make sure that we ought to have an L statement,
05:07which we do that through using the colon.
05:10And then I'm gonna set here, no,
05:11basically saying return back in this value.
05:15If this is true, return back this.
05:17If this is, if it's not true, then return back null.
05:20Now one more thing to note before we test this out is
05:23that our image here, notice
05:24how we have your just a self enclosed node.
05:28And in reality that is exactly how it's supposed to be.
05:31I could send an ode to a full node such as this,
05:34but I can never send in two nodes, one
05:37after each other as a single element.
05:39'cause again, anytime we refer to JSX, it has
05:41to be a complete JSX, it has
05:44to be a complete valid XML, which means only one root.
05:48Okay? So that's it.
05:49Let's go ahead and take a peek and see if anything changed.
05:52If nothing broke, this is exactly what we would hope.
05:55Now notice what will happen if we
05:56Change our initial state to be false
06:00by setting it to false.
06:02Our has image is not gonna be there anymore
06:04and our images are not gonna start up at all.
06:06Beautiful. So now that we set that
06:08and it's working, it's time for us
06:10to actually activate that state.
06:11And the way I'm gonna do that is by adding into our,
06:15into our element here, into our div itself.
06:18I'm gonna go ahead and add to it, uh, on click state.
06:22Now the on click state, I'm again gonna send
06:24inside using our round our curly brackets,
06:28what is the method that I want to call?
06:30I'm just gonna create a call that's gonna be called,
06:32let's say this dot uh, on update
06:38image state.
06:39Okay? So on update image state.
06:42Now if I go ahead here
06:43and I go into my application, well into my i,
06:48into my uh, class itself and create this function.
06:50So first of all, we're not expecting
06:52anything although it is an event.
06:54So we might be getting their event,
06:55although we just are not gonna actually refer to it.
06:59But what we wanna do is once we're inside of this function,
07:02what we really want to do is we want to go to this dot.
07:04Oh, by the way, let's double check that.
07:06If I do hear a console dot log, if this remains the same,
07:10will it be this of our class
07:12or will it be this of our diviv itself?
07:14Let's give it a look and see what actually happens.
07:18So if we go ahead here
07:19and we click on something, let me just open this up.
07:21Oh, and you let me get rid of all those, uh, traces.
07:24So got rid of that trace and let's click on here
07:27and see what's gonna come back.
07:29So first of all, we could see that we're getting back, no,
07:31it is not identifying our this and that is
07:34because it's a losing scope, which is kind of logical
07:36because we're setting here a click event
07:38and it's not directly connected to our class anymore.
07:42Now, a wonderful way
07:43to solve this problem in ES six is in my construct
07:46or really anywhere before I start using it.
07:49I could go and just set this on update image state
07:53equals I'm basically gonna override its normal behaviors
07:57and bind them to this.
08:00And what I've done by that is I basically said,
08:01anytime I call this function, I wanna make sure my,
08:05this is considered the class as this override whatever
08:09defaults are gonna happen.
08:11And if I go back into my application and let it refresh
08:14and click here, we'll see that now we're getting access
08:16to our object, which is exactly what we wanted.
08:20So now that we have access to our object, I could go
08:23and say this set state, and I'm gonna go ahead here
08:27and open a bracket and close a bracket
08:30and open a curly bracket
08:31and close a curly bracket, curly bracket.
08:33And I'm just gonna go ahead here and set it from true.
08:36I'm gonna go ahead and send it to false.
08:39Now I want you to notice another something
08:40that has just happened here.
08:42I did not set my state by going to this
08:46state has image.
08:49The reason is is very simple
08:50because we wanna make sure that we're declaring
08:52to react that something has
08:54Changed here.
08:55Now, this is really important
08:57because we don't wanna make any changes
08:59to a component without broadcasting to the world.
09:02In reality, we're never gonna go and re-render something.
09:04Instead of that. We're declaring to the world
09:06that something has changed
09:08and react on its own is gonna call render again
09:10after it changed the state
09:12and also call any other elements it need to.
09:15So react is gonna be managing what needs
09:17to be re rendered and not us.
09:19So we're gonna take a deeper look into
09:20that really, really soon.
09:22But if we go ahead and we just run our application just one
09:25more time and let me just close it up here.
09:27We'll see that now when I click on an item, it will go away,
09:30go away, go away, and go away.
09:34Now our only problem is, is that it'll be very hard for us
09:36to bring it back because we didn't add that logic in at all.
09:41But that's what we'll do in the next lecture
09:42as we explore a few more new things in E ES six.
09:47In this lecture, we really differentiated
09:49and understood what is the difference
09:51between props and state.
09:53And in the next lecture we're gonna go ahead and continue
09:57and understand really the it it wrap up everything we've
10:00done throughout this chapter
10:01and understand how React works
10:03as we introduce another ES six uh, feature, which is arrow
10:07functions.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!