React Beginner: Part II

Murli Prajapati
Bit Shift
Published in
5 min readMay 13, 2018

Understanding bare bones of React component

This is the second part of React Beginner series where we are creating a simple responsive weather app using React. In first part, I talked about setting up React project from scratch. Go here and setup your project.

Disclaimer: I’ve tried to make this article independent of our weather app so that It can serve as a quick guide to other readers plus it contains 70% theory and 30% code.

React component:

From React docs: Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

As in divide and conquer method we divide the bigger problem into smaller ones and repeatedly solve the single smaller problem independently to solve the whole puzzle, in React or any other UI framework out there the whole UI is sub-divided into smaller functional parts. Each part holds the logic for how it should display itself on the screen and how to handle user interaction, and maintain its state.

So in terms of web development, a component is comprised of a bunch of HTML tags, some styling using CSS and quite a bit of JS to handle the interaction.

React introduced or imposed a new way of writing HTML, which is JSX (JavaScript syntax Extension). JSX allows us to write the same HTML code in JavaScript and this JSX code gets compiled to the old react-way of creating HTML component using Babel. Once the old react-way component is created, react converts it to native HTML element.

So you must be asking how the heck a “React Component” look like? So let’s look at one.

Any UI in React is composed of either of these two types of component. Functional (Stateless) and Class (Stateful).

Functional component:

A functional component is just a JavaScript function that returns HTML markup using some passed properties. This kind of component is created when its job is just to display some data. They do not have any user interactions. That’s why they don’t need any state.

In code snippet shown above, UserProfile is a functional component which displays user’s profile picture and name.

The way UserProfile component gets info about the name and imgUrl is by using props (properties).

Properties (props):

Props are additional info passed to components as JSX attributes. It is exactly same as how we pass attributes in HTML. Any prop passed to the component is accessed using this.prop.propName and props are read-only.

Class component:

A Class component does a bigger job than functional one. It holds state and interactions. Whenever we create a component using ES6 class it gets its own state variable.

A class component must implement render method because that’s how React will know how to show it on the screen.

The state is initialized in the constructor of the class and it is updated using setState() method because the setState method will trigger the re-rendering of components with new state value (Explained below).

The UserList component shown above comprises the user data in its state and the state is then used to generate single UserProfile list item component using renderUserList method.

Notice how we are passing the name and imgUrl to UserProfile component. That’s how props are being passed to other components.

Also, we are using className instead of class in UserProfile component as class is reserved keyword in JS.

Note: Whenever we want to write any js syntax in JSX we write it in { } curly braces. Look how renderUserList method is called inside render() method.

So now you know a bit about React’s components, let’s quickly talk about component’s state and lifecycle then we will start creating our app.

So what is state?

State is a piece of information that helps component to define its behaviour, interaction and rendering. For e.g., a search bar’s behaviour is to get search result whenever the user hits enter key or presses search button. So the state will have information about what text was entered and using that value component will handle the search submit interaction.

In React, state is a JSON object which holds key-value pairs. As you can see in the above code snippet state has userData array. A state object has to be immutable which means that values of state should not be updated by directly referencing them instead they should be reassigned.

Let’s take an example.

In code shown above, assume that UI has a button to add new user to userData in state.

You may think what’s wrong with the first method as this is how we add new elements to array but the issue comes in rendering part. When anything is drawn on screen it can only be updated by re-rendering the whole thing and React handles the job of rendering.

The component has drawn itself using the old userData variable which had two elements. Now, to display third element on screen it has to re-render itself. So, how will React come to know that it has a job to do? No, it will not know because it is not listening for any changes in state.

That’s where setState method comes to rescue. setState method takes an object containing new state values and tells React to re-render the component. We can also pass a function that enables us to access the previous state values. So in second method, we are reassigning new value to userData by creating a new array and adding previous and new values. Since setState will cause re-rendering, the third element will be displayed on screen.

I hope now you know why state mutation should be avoided.

Component Lifecycle:

As with any other UI framework, React’s components also born, grow and die. So to be a part of these stages of a component React has provided some lifecycle hooks/methods.

Image credit: https://twitter.com/pbesh

Now let’s consider the UserList component shown in above code snippet.

UserList will go through the methods in “First Render” when it is going to be added to the DOM. That’s how our component is born.

Suppose because of some user interaction state of UserList gets changed so, that will trigger the “State Change” methods of UserList and will re-render itself and its children. Our component is growing.

A method in “Unmount” will be called when UserList will be removed from DOM. Our component just died.

These are some important and frequently used hooks. There are many lifecycle hooks associated with a component which you can find here.

Things to note:

1. Always initialize state in constructor.

2. constructor, componentWillMount and componentDidMount are called only once in the entire lifecycle of the component.

3. Component is re-rendered on prop and state change.

4. Do not change state in componentWillUpdate (Look for setState OK and NO setState in above lifecycle diagram).

5. Always use setState() method to update state.

With this very long theoretical article we are all set to dive into creating components for our weather app.

Meet me there at the third installment of this series: React Beginner: Part III

If you liked this article don’t forget to clap 👏. If you have any suggestion or query feel free to post here in comments or ping me on twitter.

--

--

Murli Prajapati
Bit Shift

Full Stack Developer | Android Developer | Hobbyist Gamer