For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogWeb DevelopmentWhat Is a React Component? Write Your First React Component

What Is a React Component? Write Your First React Component

Published
05th Sep, 2023
Views
view count loader
Read it in
12 Mins
In this article
    What Is a React Component? Write Your First React Component

    Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  

    I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  

    But first, what is Component-based Architecture? 

    Component-based Architecture 

    In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. 

    What is component? 

    So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? 

    The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.

    Benefits of using Component Architecture 

    There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: 

    • Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. 
    • Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. 
    • Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. 
    • Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.

    React Components 

    React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? 

    A very simple components looks something like this:

    import React from "react"; 
    function Greeting({ name }) { 
      return < h1 >{`Hello ${name}`}</h1>; 
    } 
    ReactDOM.render(<Greeting name="Gully Boy" />, document.getElementById("root"));

    Alright. But<Greeting /> is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  

    JSX 

    JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. Igives a syntax { <Any JS code >}, inside curly bracket, we can write JS code. 

    But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. 

    import React from "react"; 
    function Greeting({ name }) { 
      return React.createElement("h1", null, `Hello ${name}`); 
    } 
    ReactDOM.render( 
    React.createElement("Greeting", { name: "Gully Boy" }, null), 
    document.getElementById("root") 
    ); 

    React.create Element is part of React API which actually defines a React elementThis data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  

    Classification of React Components 

    Based on Interactivity 

    Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. 

    There are two types of components based on interactivity: 

    • Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component <Greeting name="John Smith" /> is a stateless component as it just renders the information (in this case name props) passed to it. 

    • Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:

    import React, {useState} from 'react'; 
    function Counter() { 
    const [value, setValue] = useState(0); 
    const increment = () => { 
    setValue(value + 1); 
    } 
    const decrement = () => { 
    setValue(value - 1); 
    } 
    return ( 
    <div> 
    <button type="button" onClick={increment}>Decrement</button> 
    <span>{value}</span> 
    <button type="button" onClick={decrement}>Decrement</button> 
    </div> 
    ); 
    } 
    export default Counter;

    Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

    Based on Programming Methodology 

    Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

    Based on Programming Methodology 

    There are two type of components based on Programming Methodology 

    • Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:

    import React from 'react'; 
    class Greeting extends React.Component { 
    constructor(props) { 
    super(props); 
    } 
    render() { 
    return < h1 >{`Hello ${this.props.name}`}</h1>; 
    } 
    } 
    export default Greeting; 
    • Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. 

    Based on Functionality 

    There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. 

    • Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. 

    • Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.

    Component and its lifecycle 

    In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  

    React lifecycle

    React lifecycle. 

    To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting 

    • Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:

    • constructor 

    constructor(props) { 
    super(props); 
    // code here 
    }
    • getDerivedState From Props 

    static getDerivedStateFromProps(props, state) { 
    // code here 
    // return updated state object or null 
    } 
    • render 

    render() { 
    // code here 
    } 
    • componentDidMount 

    componentDidMount() { 
    // code here 
    } 
    • Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:
    • getDerivedState From Props 

    static getDerivedStateFromProps(props, state) { 
    // code here 
    // returns updated state object or null 
    } 
    • should Component Update 

    shouldComponentUpdate(prevPropsprevState) { 
    // code here 
    // returns true to re-render the component otherwise return false.  
    // default is true 
    } 
    • render 

    render() { 
    // code here 
    } 
    • getSnapshot Before Update 

    getSnapshotBeforeUpdate(prevPropsprevState) { 
    // code here 
    } 
    • component Did Update 

    componentDidUpdate(prevPropspreState, snapshot) { 
    // code here 
    } 
    • Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:

    componentWillUnmount 
    componentWillUnmount() { 
    // code here 
    }

    Set up a React project 

    As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. 

    Create React project with CRA 

    First check the NodeJS and NPM installation on machine by executing following command: 

    node --version 
    npm --version 
    npx –version 

    In case NodeJS is not install then download and install it from. 

    Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: 

    npx create-react-app My First React Project 

    NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: 

    cd My First React Project 

    npm start 

    This would start a local server at port number 3000 and open default React page in browser.

    React page in browser

    Understanding project generated by CRA
     project generated by CRA

    Above image shows the files and folder generated by CRA. let us go through it and understand: 

    • package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... 
    • public folder: All public assets will be present in public folder like index.html, image or logo etc... 
    • src folder: All our JS code including React components will be present in src folder. 

    CRA configured our React project with all the needed tooling required for web development. It configured Webpackdev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslintreact-testing-library for unit testing React components etc... 

    src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. 

    What type of React Component should I build in 2020 

    So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.

    Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: 

    Counter component code: 

    import React, { useState } from "react"; 
    import "./Counter.css"; 
    function Counter() { 
    const [count, setCount] = useState(0); 
    const increment = () => { 
    const updatedCount = count + 1; 
    setCount(updatedCount); 
    }; 
    const decrement = () => { 
    const updatedCount = count - 1; 
    setCount(updatedCount); 
    }; 
    return ( 
    <div className="counterContainer"> 
    <button type="button" onClick={decrement}> 
    -
    </button> 
    <span>{count}</span> 
    <button type="button" onClick={increment}> 
    + 
    </button> 
    </div> 
    ); 
    } 

    export default Counter; 

    Styles are added in Counter.css 

    .counterContainer { 
    background-color: #fff; 
    font-size: 24px; 
    font-weight: 500; 
    border: 1px solid #0874ce; 
    border-radius: 3px; 
    box-shadow: 1px 1px 4px 0 #0084ff; 
    } 
    .counterContainer button { 
    outline: none; 
    border: none; 
    width: 50px; 
    height: 40px; 
    background-color: transparent; 
    font-size: 24px; 
    font-weight: 500; 
    cursor: pointer; 
    } 
    .counterContainer span { 
    color: #0084ff; 
    } 

    We have created a fully functional counter component which can be used anywhere in React application.

    Looking to dive into the world of data science? Discover the power of data with our unique courses. Unleash your potential today! Explore our data science courses and fees.

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon