How to import images dynamically in react?

By Prajwal Haniya

Techletter 1 | December 10,2022

  1. How to return a false, when there is an array filled with multiple empty arrays?

    I hope you will understand what I meant, in the below example:

    const arr = [[], [], []];

    const arrLength = arr.length;

    The arrLength is 3. But, technically I wanted this to return false if arr is filled with all the empty arrays because certain functions needed to be executed when you get an empty array or array with all empty arrays within.

    So here I found the solution

    let isEmpty = arr => Array.isArray(arr) && arr.every(isEmpty);
    let isArrayEmpty = isEmpty(arr);
    console.log(isArrayEmpty);
    
  2. How to Import the images dynamically in react?

    Importing images dynamically can save you much time instead of writing the same repetitive code. So, after searching & trying a lot of techniques, the code below helped me import the images dynamically.

    function importImage({logoSource}) {
        const [logoUrl, setLogoUrl] = useState(null);
        useEffect(() => {
            import(`../your-url/${logoSource}`).then(img => {
                 setLogoUrl(img.default);
            });
        }, []);
        return <img src={logoUrl} alt="" />
    }
    
  3. How to find the duplicates in an array of constants?

    This was one of the interesting problems that I have solved. To solve this problem you need to understand Floyd’s tortoise and hare algorithm. This algorithm is also called as cycle detection algorithm.

    Though this algorithm is used for linked list. we use the similar approach by creating a linked list-like structure and finding the cycle in the array of constants.

    /*
    Algorithm
    --
    1. Construct the sequence
    2. Each new element in the arr[], is the sequence 
    of the index of previous element
    let arr = [1,4,5,1,3];
    
    here, arr[0] = 1 -> arr[1] = 4 -> arr[4] = 3 -> arr[3] = 1
    
    once we find the cycle we return the number
    */
    

    Implementation:

    const findTheDuplicate = (arr) => {
        let slow = arr[0];
        let fast = arr[0];
    
        while (true) {
            slow = arr[slow];
            fast = arr[arr[fast]];
    
            if (slow === fast) break;
        }
    
        slow = arr[0];
    
        while (slow !== fast) {
            slow = arr[slow];
            fast = arr[fast];
        }
    
        return slow;
    }
    
    const arr = [1,4,5,1,3];
    console.log(findTheDuplicate(arr));
    
  4. What is a custom hook in react?

    For a beginner, this might find as a fairly complex thing to understand. But, with experience, you get this very quickly. Don’t worry if you can’t understand this at the beginning, but as you build complex applications, you will get it.

    Let me give you an example, by building a simple custom hook, which returns data by calling an API.

    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    
    function useFetchStatus() {
    	const [status, setStatus] = useState(false);
    
    	const getStatus = () => {
            //calling the API using axios
            axios.get('/api/get_status').then(res => {
                    const { data } = res;
                    if (data.success) {
                        setStatus(data.status);
                    }
            });
    	}
    
    	useEffect(() => {
            getStatus();
    	}, []);
    
    	return status;
    }
    
    export default useFetchStatus;
    

You can use the above hook in any of your components, here, to get the status that is true or false of something.

import useFetchStatus from './useFetchStatus';
const userOnline = useFetchStatus();

You can refer to the official react documentation of custom hook for a deeper understanding of the custom hook.