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

Changing Components State in React with Griddle

Changing Components State in React with Griddle

Managing state in React is crucial for building dynamic, interactive applications. In this tutorial, we cover the distinction between state and props, how to work with constructors in ES6, and how to visualize state changes dynamically with the Griddle library.


What You’ll Learn

  1. React State Basics: Understand the difference between state and props in React.
  2. Binding Methods: Retain the correct scope for class methods in ES6 using .bind().
  3. Dynamic Rendering: Use this.setState to update your UI in response to state changes.
  4. Visualizing Data with Griddle: Render data dynamically in a grid format using the Griddle library.

Step 1: Setting Up the Constructor

The constructor is a special ES6 method in React classes that initializes the component state. To ensure props are passed correctly to the React component, you must call super(props) inside the constructor.

Here’s the basic setup:

constructor(props) {
    super(props);
    this.state = {
        cities: [] // Initial state
    };
    this.onClick = this.onClick.bind(this); // Retain scope
}

Key Point: Binding methods like this.onClick ensures the correct this reference inside event handlers.


Step 2: Managing State

State updates in React trigger UI re-renders. Use this.setState() to inform React of changes:

this.setState({ cities: JSON.parse(xhr.responseText).geoNames });

This updates the cities array in the state with data fetched from the web service.


Step 3: Installing and Using Griddle

To visualize data, we leverage the Griddle library:

  1. Install Griddle:
    npm install --save griddle-react
    
  2. Import and use Griddle in the render method:
    import Griddle from 'griddle-react';
    
    render() {
        return (
            <div>
                <img src="map.jpg" alt="Map" />
                <Griddle results={this.state.cities} />
            </div>
        );
    }
    

Note: Griddle simplifies displaying data in tabular format, making it easy to render dynamic content.


Final Thoughts

This lesson introduced essential React concepts like state management, scope binding, and dynamic rendering. Mastering these techniques helps build responsive and interactive applications.

Explore the full course to dive deeper into React’s advanced features and data visualization techniques:
React Data Visualization Course

2024

The approach outlined in this video is a solid foundation for understanding React, but some parts might feel dated for new projects in 2024. Let’s assess the practices:


1. Managing State in React

The state management techniques shown (using class components and this.setState) are still valid but not the modern standard for React.

Updated Recommendation:

React introduced hooks in version 16.8, which have become the go-to way to manage state and side effects in functional components.
Instead of class components and constructors, consider using useState and useEffect:

import React, { useState } from 'react';

function MapComponent() {
    const [cities, setCities] = useState([]);

    const onClick = () => {
        // Fetch data and update state
        fetch('your-api-url')
            .then(response => response.json())
            .then(data => setCities(data.geoNames));
    };

    return (
        <div>
            <button onClick={onClick}>Get Cities</button>
            {cities.map(city => (
                <div key={city.id}>{city.name}</div>
            ))}
        </div>
    );
}

2. Using Griddle for Data Visualization

Griddle provided a good way to render grids dynamically in 2016. However, its development has slowed, and newer libraries offer more robust features.

Updated Recommendation:

Consider libraries like Material-UI's DataGrid or AG Grid, which are actively maintained, offer more flexibility, and integrate seamlessly with React.

For example, with Material-UI:

npm install @mui/x-data-grid
import { DataGrid } from '@mui/x-data-grid';

const columns = [
    { field: 'id', headerName: 'ID', width: 90 },
    { field: 'name', headerName: 'City', width: 150 },
];

export default function GridComponent({ cities }) {
    return <DataGrid rows={cities} columns={columns} pageSize={5} />;
}

3. Fetching Data with XMLHttpRequest

The tutorial uses XMLHttpRequest to fetch data, which is now considered outdated. Modern projects use the Fetch API or libraries like Axios for more concise and powerful HTTP requests.

Updated Recommendation:

Use the Fetch API or Axios:

fetch('your-api-url')
    .then(response => response.json())
    .then(data => console.log(data));

Or Axios:

npm install axios
import axios from 'axios';

axios.get('your-api-url').then(response => console.log(response.data));

4. Scoped Functions and Arrow Functions

The bind method for maintaining this scope is unnecessary in modern React. Instead, use arrow functions in functional components or inline event handlers.


Final Verdict

For new projects in 2024, adapt the tutorial concepts with these updates:

  1. Use functional components with hooks like useState and useEffect for state management.
  2. Replace Griddle with modern, actively maintained libraries like Material-UI's DataGrid or AG Grid.
  3. Use the Fetch API or Axios for HTTP requests.
  4. Embrace arrow functions to simplify event handling and maintain scope.

These updates align with React's modern ecosystem, improving code readability, maintainability, and performance.

Video Transcript

00:00In this last, last lecture,
00:02in this section we're gonna learn about state,
00:05which is different than properties in React.
00:08We're gonna understand what they are
00:09and what their difference is from properties.
00:13With that said, we're also gonna connect our map.
00:16We're gonna learn how to keep our scope.
00:18We're gonna learn how to work with a constructor.
00:21And moreover than that, we're, we're gonna learn how
00:24to use the React state.
00:25And in the process we're gonna introduce you to griddle
00:28a a component that enables you very easily
00:31to add visual grids onto your screen.
00:34So let's jump right into it. Okay.
00:37It's time for us to connect the dots
00:39and the last step that's left for us
00:41to do is actually visualize the change
00:43and actually get our component to be aware
00:46of a change of its state.
00:48And that's exactly how it is called.
00:50So let's go ahead and create that.
00:52I'm gonna go into the beginning of my class
00:55and I'm gonna create a new function called a constructor.
00:59And again, this is also part of those new things in E ES six
01:03where the constructor itself is basically a function
01:07that is automatically called
01:09whenever you're creating a new instance of a class.
01:13Now, specifically the component class expects inside
01:17of the constructor to have a props
01:20property more accurately.
01:22We need to go ahead and send whatever is happening in the
01:25constructor to the constructor of React.
01:28So to do that, I'm gonna go ahead and call the command super
01:31and then send in the props so
01:33that way our react component could take care of the props,
01:36making sure that they'll be available
01:38to us throughout the application.
01:41The next thing that I want to do is I wanna show you how
01:44to solve that problem of scope
01:46that we're gonna encounter in our on click.
01:48As you saw, when we try to do a log inside of
01:53here, we didn't get our this.
01:56So really the reason is
01:57because we're not getting that this here either.
01:59So literally, if I go ahead here
02:01and I just run my application just one more time
02:04and we click somewhere, we'll see that we're getting null
02:06and null so it's not passing through.
02:08Although this function method,
02:11which is called an arrow function,
02:12automatically captures whatever that this is outside of it.
02:16So in our case, to make sure
02:18that our on click always keeps scope
02:21and doesn't change any scope in my constructor,
02:24I'm gonna go ahead and ask to change the on click
02:27to be the on click, the bind to this,
02:31making sure that anytime on click is being called, it's,
02:35this will remain the same.
02:37Now if I go ahead and save that
02:38and check it out in my application one more time, we'll see
02:41that we're not gonna lose our scope anymore perfectly
02:44because we really need access to that scope now
02:47that we're gonna start working on states.
02:50So I'm gonna go ahead here
02:51and I'm gonna create that state variable.
02:53And by the way, this works with built in to React.
02:57What I'm gonna do is just define
02:58An object that's gonna have inside a few properties.
03:01For example, in this case, I just am going to have cities
03:05and by default it's gonna be an empty array of cities.
03:09In reality, our web service will return to us
03:13multiple cities whenever we're clicking
03:14on a place which has cities.
03:16Now that I defined a state,
03:18and I know my component now knows
03:20that it should expect something to change
03:23once something changes.
03:25For example, when we're inside of this on click event
03:28and we got that information back literally inside
03:31of this line 36 where we were looking for our, this area,
03:35what we wanna do is we wanna declare to react
03:39by the way, something changed.
03:41To do that, I'm gonna call this set state.
03:44And the set state expects an object of state.
03:47And I'm gonna go ahead here
03:48and just override that city's parameter, accepting the value
03:53as we saw previously, which is our XR
03:57response text.
03:59Now this is not good enough
04:00'cause I don't want it to come back
04:01as a string as it is right now.
04:03I want to convert it into JSON.
04:05So to do that, I'm gonna use the builtin JavaScript feature
04:08of JSON, do Parse,
04:11and I'm just gonna wrap it around there, making sure
04:13that my response is gonna be in JSON and just also, also,
04:17'cause I already know in advance, the value
04:18that is gonna come back is gonna sit all inside
04:21of a property called Go Names.
04:24So I know it's gonna be in there.
04:26So I'm gonna cut through that, go names
04:27and just get all those cities, all those city names.
04:31If I go ahead and save this,
04:33I'm not gonna see anything change yet
04:35because we don't have anything visually changing.
04:38Although what's actually happening,
04:40it's Tell React is telling itself, Hey, you probably need
04:42to refresh, check to see if something needs
04:44to be updated in our case.
04:46'cause we're not actually adding anything,
04:47we're not seeing a change.
04:49So let's go ahead and change that fact
04:51that we're not changing anything.
04:53And to do that, what I want to do is I want
04:55to use a third party tool
04:57to basically list out all the values
04:59that are coming through.
05:01To do that, I'm gonna stop our server and I'm gonna go
05:04and ask from NPM to install and I'm gonna go ahead
05:07and save it because we're gonna need it in our production.
05:10We're gonna install griddle do slash react.
05:14Griddle slash react is literally a library that enables us
05:18to create grids inside of our application very easily.
05:22Now that it's I installing while it's being installed,
05:24I'm gonna go ahead and import it
05:26and I'm gonna import griddle from Griddle React.
05:32And now that I have access to griddle,
05:34I'm just gonna go ahead immediately, directly
05:36and change our body of our rendering
05:39because I want to include oto, that grid.
05:41So lemme just go ahead and break lines here a little bit
05:45and I'm gonna close that Diviv as well.
05:47But now that I'm sending that image, I'm gonna go ahead
05:49and also call for a new griddle.
05:51Oh, let me just move everything
05:53so you can see it more easily. Move, uh,
05:56Yeah, that's what I was saying.
05:57And it expects a property called results
06:00where we'll actually send inside the,
06:02the data itself that it's expecting.
06:04In this case, I'm gonna go to my state cities
06:07and what's actually gonna happen now is,
06:09and by the way, um, documentation for griddle is
06:12provided as well where you could explore a lot more things
06:14that you could do with griddle.
06:16But if I go back into my browser
06:18and this time around, just go ahead here
06:20and lemme just clear a little bit of that noise
06:22and click somewhere.
06:23Oh, by, by the way, our server is not running yet
06:25so we have to make sure that it's running.
06:27So lemme go ahead and call NPM start
06:31and our server should be running now.
06:33So let's go ahead here and let's clear that nonsense up.
06:37Oh, here we go. And let's clear that up.
06:38And let's click here somewhere
06:40and what's gonna happen, it's gonna return to me an object
06:43and also build out a list with all the cities
06:45that have specific names.
06:47So for example, if we go to, to this area,
06:49which I believe is Mexico,
06:51we should now find different cities inside of Mexico.
06:55Let's double check if that's really Mexico.
06:58Do we have here any Mexico City? Let's double check.
07:02And by the way, one, one thing has also,
07:04we might not be incredibly accurate with our calculations,
07:06but we are more
07:08or less
07:11accurate in this election.
07:14Sure. We leverage griddle, we learned about state
07:17and we've learned a lot of more ES six features that relate
07:20to components in general.
07:22And scope in the next section is gonna be dedicated
07:25to a new source type where we're gonna take a look at
07:29CSV files and through them we're gonna create a bar chart.

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!