skip to Main Content

I am making a const map in typescript as

export const CUSTOM_MAP = {

  'a': 'some text',
  'b': 'some text',
  'c': 'some text',
};

I want to extract the values from CUSTOM_MAP on the basis of key matching with some passed value as below and return some JSX.Element from that function to DOM.

But the below code is not returning the JSX.Element after if (key === errorStatus) condition get true.

May be I am not able to return in proper way. Please let me know how to return the JSX.Element from map() block of functionName().

// Function which is faulty.

const functionName = (errorStatus: string): JSX.Element => {

  Object.entries(CUSTOM_MAP).map(([key,value]) => {
    if (key === errorStatus) {
      // below code is not able to return from here to where the functionName() is called
      return (            
        <>
          <div>
            Some html code with this {value}
          </div>
        </>
      );
    }
  });
  return <>
  </>;
};

export default errorCasesHandling;

3

Answers


  1. You are missing a return in front of Object.entries. Try the following code:

    const functionName = (errorStatus: string) => {
      return Object.entries(CUSTOM_MAP).map(([key, value]) => {
        if (key === errorStatus) {
          // below code is not able to return from here to where the functionName() is called
          return (
            <>
              <div>Some html code with this {value}</div>
            </>
          )
        }
      })
    }
    
    Login or Signup to reply.
  2. You can do like that:

    const functionName = (errorStatus: string): JSX.Element => {
      let elements: JSX.Element | null = null;
      Object.entries(CUSTOM_MAP).map(([key,value]) => {
        if (key === errorStatus)
        {
          element = (            
           // jsx elements
          );
        }
      });
      return elements || <></>;
    };
    
    export default functionName;
    
    Login or Signup to reply.
  3. your code has some issues:

    • first of all the you are trying to return an array of JSX elements, so the type of return values should be JSX.Element[].

    • second, you didn’t return the result of the map function;

    • beside that, I guess you wanted to return <></> if the condition key === errorStatus not satisfied but you put it outside of map. so your code will be like:

    const functionName = (errorStatus: string): JSX.Element[] => {
      return Object.entries(CUSTOM_MAP).map(([key, value]) => {
        if (key === errorStatus) {
          return (            
            <>
              <div>
                Some html code with this {value}
              </div>
            </>
          );
        }
        return <></>;
      });
    };
    

    at the end if i misunderstood the third item that I said, you can use a filter function before the map;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search