React Class Components

     To further practice React, I worked on a small, simple project from this PluralSight course by Samer Buna. I decided to throw that project into an actual React app, rather than using his great Playground tool. The project is just a simple form where a user can type in a GitHub username and it will be added to the list with their profile picture, name and company.

    This simple project uses a few components, and it shows how to pass data down to child components, how to update data in a parent component from a child component. It also shows how to communicate with an API using Axios, a very common library for making HTTP requests to the browser. Class components reminded me a lot of Blazor components, we simply create a component which will have a render() call to display our HTML, and when we call that component we will pass data to it which will be available in our props object.

See Below how the CardList component is called and given data:

 

And how a component then accesses that props object:

 

     Our CardList is actually not a component class; this is the other way to write functions, and it's a bit simpler, since our component is only a single line. It actually builds a list of Card components, which will contain all the data from our API call. However, you'll notice from our code that the list of profiles we are passing down to CardList and then to Card come from our API call, which is in our Form component, so how are we passing that data between siblings?

    Really we aren't. React components play a game of telephone to send data up or down, but never side to side. The Form component is passed down a function reference, onSubmit(), which can then pass the profile data we pull from our API back up to our parent component, and down into another child component. 

 

    The result is a simple project where the Form uses axios to search for a username, send it up to our App and then down to our CardList and Card components, where a GitHub profile is displayed, and it looks like this!

 

You can check out the code here!

Comments

Popular posts from this blog

API's in C#

Using WebRTC to build a videophone in React and TypeScript

Reviewing WPF and MVVM