Full stack Web Development

React Component

In the last blog, we discussed JSX and its relation to the React component. In this blog, we look at the React component in greater detail. More specifically, we will understand how to pass the data from one component to another using props and state.

What is React Component

Components are the core building blocks of React apps. Actually, React is just a library for creating components.

To prepare a React App, you need to have a root component as (App) and then you can create a number of nested components for preparing any scalable complex application using React library.

Each component returns/ renders some JSX code and it defines which HTML code React should render to the real DOM in the end. JSX is NOT HTML but it looks a lot like it.

Differences can be seen when looking closely though (for example className in JSX vs class in HTML).

JSX is just syntactic sugar for JavaScript, allowing you to write HTMLish code instead of nesting React.createElement(…) calls.

When creating components, you have a choice between two different ways that are described here:

  1. Functional components (also referred to as “presentational”, “dumb” or“stateless” components – we will discuss more about this later in this blog series)example:-
    const cmp = () => { 
         return <div>some JSX</div>
    }

    (using ES6 arrow functions as shown here is recommended but optional)

  2. class-based components (also referred to as “containers”, “smart” or “stateful” components)Example:-
    class Cmp extends Component { 
         render () {
             return <div>some JSX</div>
         }
    }

    We’ll, of course, dive into the difference throughout this course. You can already note that you should use 1) as often as possible though. It’s the best-practice.

The above figure explains the different layouts of an application. We have one root(App) Component and under root component, we have child components.

Every component is a separate entity and not dependent on others. So, if we change one component structure it won’t affect other components.

To understand Components in React, consider the following examples:

This is the structure of the app file as below

We have created an UserApp. As you see in the above screen, we have created UserList folder. Inside UserList, we have created two subfiles as User.js and other Users.js.

In User.js we have created a functional Component using ES6 arrow function =>.

Explanation of the code:

  1. In User.js we have imported React libraries from react package.
  2. We have created const keyword to define User function using => arrow function ES6 syntax.
  3. We have passed props as a parameter to User functional Component.
  4. We are returning something, which looks like an HTML code, but this is JSX.
  5. Inside the JSX expression, we have two things – props.children and props.age.
  6. We are returning List of Users so we have passed User functional component to Users class Component as a nested component. It passes a number of Username and age.
  7. Users Component will make you understand how props receive the User data.
  8. As we have defined User in User components multiple times, prop receives  props.children.

Anything that has been passed inside <User></User> is considered as props.children.

Explanation of code:

  1. In line 2 we have imported User Component from User.js file.
  2. Inside div tag, we have passed multiple User components and for each component, we have passed the props called age. This is a String.
  3. Users component is a Class component which extends React Component.
  4. Users component is passed to App component which displays the list of Users.

Explanation of the code:

  1. As you see in the above screenshot, an App.js file which returns Users Component.

Basically, it renders the list of UserList. However, this is hard-coded data. To make it dynamic, we need to create state Object. The below example will help you understand how to use state in a Component.

Tips: It is always recommended to create a state Object inside the constructor of a Component. We can’t have a state in functional Component.

Now to pass the age through User component we will pass the props as:

“this.state.users.age[0]” describes a need to pass the props. The state will be available by using “this” keyword, which contains the array of user objects.

Now if you want to access the name in dynamic mode, you can write it as:

The data now got displayed dynamically.

If you want the title to be reflected above the Users list, then you can add title property inside state Object in the following manner:

At last, we have a title “UserList”, which is displayed from the div tag.

Line 35 justifies how to access the title value. In line 33, we have created a button which will change our state property age. Remember we can’t change the state of the Object directly. To change our State property we have to use the setState() method.

The advantage is it will only update the age rather than reloading the entire DOM again. So let’s demonstrate setState() and the virtual DOM concept.

UserList that got rendered along with this button has also been created. Now if we click on the button it should update the Age. Let’s add some event by using function and passing it to the button so that it will listen to us.

If you try to change the state directly, you will get a warning as below :

Line 34 is not the way to implement the user’s age property and update it to 3 years older.

The correct approach is the setState() method to update state properties.

Inside setState() we have passed the Array of Objects to update age property dynamically. If we update it without using the setState() method, then React will not acknowledge or update it in the DOM.

Final Code

Now, let’s use array helper method map() to iterate and update the list of Users age value.

As we can see, there is the method called MakeOlder(), which is invoked by clicking the button. Inside MakeOlder() method, we will update the age of all the users and assign it to const newState.

We will then update the existing state with the new state using the setState() method.

When we click on “Make Age 3 years older”, then the age is dynamically updated in the DOM without reloading the entire page.

Virtual DOM

Virtual DOM is a copy of the actual DOM, which React uses for smart rendering. Any change or update will be first applied to virtual DOM. React then compares Virtual DOM with Actual DOM and renders the difference.  In the next blog, we will go into detail about this concept.

Conclusion

Component plays a vital role in creating a React App. In the coming blogs, we will understand the life cycle hook of the component.

Som

is a full-stack web developer, designer, and educator who has been building user interfaces for over a decade. He’s done work for Fortune 4 companies, national political campaigns, and international technology leaders. His proudest achievement is helping people learn full-Stack web development.

4 Comments

  1. Awesome explanation ,Sir I have one more doubt,when in user.js Is it necessary to write super() as first statement inside the constructor ?
    Why or why not ?

    1. super() keyword is necessary and in case you haven’t written in the constructor, you will get an error. super() keyword help us to call the React Component constructor in our user-defined Component.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close