Metadesign Solutions

A Practical Guide to Creating Reusable React Components

A Practical Guide to Creating Reusable React Components
  • July 6, 2022
  • Sukriti Srivastava
  • 7 minutes read

Blog Description

A Practical Guide to Creating Reusable React Components

React is undoubtedly one of the world’s most popular and most used frameworks. Still, many developers don’t know how to use refactoring codes for development.

In Vanilla JavaScript, you need to write codes as a function to use the same codes. In the case of React, you must write your codes as components, and you need to create a class of codes and reserve them in that class. So, this blog is on how to develop reusable React easily. Let’s start!

Usage of React components

React helps developers send information to a component using properties (Props). Props are variable objects. You will get to know many passing Props through components, and this is attributed to HTML. Components help to segregate UI into reusable particles. Each piece is in isolation, so you can only use components linked to JavaScript functions.

They take proper inputs and then return the React segment. This whole process can be seen through your computer screen. When writing reusable components, you must use powerful tools like Bit, an open-source toolchain. Bit will help you share and reuse components between projects and apps, which will help you run the app faster than ever!

Top three indicators or reusable React components

We are presenting the top three indicators of all time. Let’s look!

1) Creation of wrappers with CSS style

You can make the same class name elements in  CSS style. If you are making components with the same methods, they will share the same style. It also will introduce complexity in components. Want to see common style elements

				
					  Example
    1) // Login.js
    import './common.css';
 
    function Login() {
        return (
            <div className='wrapper'>
                <main>
                    {...}
                </main>
                <footer className='footer'>
                    {...}
                </footer>
            </div>
        );
    }
				
			
				
					  2) // SignUp.js
    import './common.css';
 
    function Signup() {
        return (
            <div class='wrapper'>
                <main>
                    {...}
                </main>
                <footer class='footer'>
                    {...}
                </footer>
            </div>
        );
    }
				
			

You can also apply these styles to containers (the <div> element). The footer of each component. You are also able to create components –

				
					 <wrapper /> and <Footer />

				
			

2) Repetitive usage of event listeners

You need to follow this example to attract event listeners to an element –

				
					/ App.js
    import { useEffect } from 'react';
 
    function App() {
    const handleKeydown = () => {
        alert('key is pressed.');
    }
 
    useEffect(() => {
        document.addEventListener('keydown', handleKeydown);
        return () => {
        document.removeEventListener('keydown', handleKeydown);
        }
    }, []);
 
    return (...);

				
			

3) Repetitive usage of GraphQL script

If you are making GraphQL, you don’t need to look for signs. In Complex applications, GraphQL scripts take 30-50 lines of code to do mutation and query. If you are using a GraphQL script, then it has its custom hook.

Follow this example –

				
					import { gql, useQuery } from "@apollo/react-hooks";
 
    const GET_POSTS = gql'
    query getPosts {
        getPosts {
        user {
        id
        name
        ...
        }
        emojis {
            id
            ...
        }
        ...
    }
    ';
 
    const { data, loading, error } = useQuery(GET_POSTS, {
        fetchPolicy: "network-only"
    });
				
			

Hope these three indicators will sort out
your problem.

Create three Reusable React Components

You can now create components when the
situation requires you to do so. New components can be shared
through React
applications
. We have placed three practical examples here:

1) Layout Component

React is used by developers for creating
complex web applications. Many pages are developed through React,
and every page may have a different layout. So, this fetch policy
comes with complexity. There can be a website of 40 pages but it may
require less than five different layouts for all of these pages as
the fetch policy will be reusable. So, building a flexible, reusable
fetch policy on other pages is essential. This will save you time
and pressure to write lines of code.

Follow this React Functional
Component –

				
					 
    import style from "./Feed.module.css";
 
    export default function Feed() {
    return (
        <div className={style.FeedContainer}>
        <header className={style.FeedHeader}>Header</header>
        <main className={style.FeedMain}>
            {
            <div className={style.
    
				
			

2) Event listener

How about we create a Custom React hook? We need to learn this through the useScrollSaver hook. This is Dave’s scroll position of a user’s device, and users don’t have to scroll again and again to reach the top. This is an excellent feature for web pages.

Follow this example –

				
					 
    // useScrollSaver.js
    import { useEffect } from "react";
 
    export default function useScrollSaver(scrollableDiv, pageUrl) {
    /* Save the scroll position */
    const handleScroll = () => {
        sessionStorage.setItem(
        '${pageurl} - scrollPosition',
        scrollableDiv.current.scrollTop.toString()
        );
    };
    useEffect(() => {
        if (scrollableDiv.current) {
        const scrollableBody = scrollableDiv.current;
        scrollableBody.addEventListener("scroll", handleScroll
				
			

See the useScrollSaverhook. t needs items scrollableDiv and <Main> to contain the layout. PageUrl is also used for multiple positions.

3) Query / Mutation ( specific to GraphQL)

If you want to use GraphQL with React, then you need to reduce the codebase. Follow the given example to create a React Hook for GraphQL.

Example Code:

				
						 
    import { gql, useQuery } from "@apollo/react-hooks";
 
    const GET_POSTS = gql'
    query getPosts {
        getPosts {
        user {
        id
        name
        ...
        }
        emojis {
            id
            ...
        }
        ...
    }
    ';
 
    const { data, loading, error } = useQuery(GET_POSTS, {
        fetchPolicy: "network-only"
    });
				
			

Note: Use this React Hook for better results.

Use functional components

Your component’s purpose is to show data. We advise you to write components in a functional way instead of writing class  components. We can also show you typical class components converted into functional components.
 

Typical class component

				
					 
    React. Component {render() {return (
        <div>This could've been a functional component</div>
    )}}

				
			

Now let’s convert this component into a functional component

				
					 
    const Hero = () => <div>Functional Components are so simple!</div>
    

				
			
Both these solutions define the Hero component. However, the difference is that the second method is more straightforward and shorter than the first.

NOTE: Use functional components only in certain situations, not in every situation.

Conclusion

You have now learned to use reusable components without using similar elements. You may think it’s easy to reuse the components without any edits, but it’s not. Even for minor edits in the codebase, a user has to make changes in the code class. However, with reusable components you will save a lot of time and product development will become easier. If you still have doubts or queries, check out MetaDesign Solutions for a better understanding.

0 0 votes
Blog Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Scroll to Top

GET a QUOTE

Contact Us for your project estimation
We keep all information confidential and automatically agree to NDA.