Home > Mobile >  How to remove Blank Spaces from the React app if there is no data available for it?
How to remove Blank Spaces from the React app if there is no data available for it?

Time:10-10

Currently, I am working on a Dictionary App in React through an API. In this API, some words have synonyms while some do not and the same is with antonyms and examples. I want to display them if they are, but if they aren't, I want to display "data not available". And also want to display them without any white spaces. Can anyone help me? This is the live link. Here is the code for antonyms -

    import React from "react";

    const Antonyms = ({ mean }) => {
      return (
        <>
          {mean.map((Val) => {
            return Val.meanings.map((Means) => {
             return Means.definitions.map((Def) => {
               return (
                <>
                 <li className="text-capitalize fs-5 text-start">
                  {Def.antonyms}
                </li>
              </>
            );
          });
        });
      })}
    </>
  );
};

export default Antonyms;

CodePudding user response:

You can use conditional rendering as follows based on the existence of Def.synonyms value. If it's undefined or null, then component won't be shown.

Read more on conditional rendering here.

import React from "react";

const Synonyms = ({ mean }) => {
  return (
    <>
      {mean.map((Val) => {
        return Val.meanings.map((Means) => {
          return Means.definitions.map((Def) => {
            return (
              <>
                {Def.synonyms ? (
                  <li className="text-capitalize fs-5 text-start">
                    {`${Def.synonyms}`}
                  </li>
                )}
              </>
            );
          });
        });
      })}
    </>
  );
};

export default Synonyms;

Or you can return it as follows to show the "data not available" quote.

            return (
              <>
                <li className="text-capitalize fs-5 text-start">
                  {!Def.synonyms ? `${Def.synonyms}` : "data not available"}
                </li>
              </>
            );
  • Related