Home > OS >  How to render <div> only if <Trans> translation string is not empty - React
How to render <div> only if <Trans> translation string is not empty - React

Time:07-13

I have array of objects in React:

const books = [
  { 
   id:1,
   name: <Trans i18nKey="books.firstbook.name",
   description: <Trans i18nKey = "books.firstbook.description"
  },
  { 
   id:2,
   name: <Trans i18nKey="books.secondbook.name",
   description: <Trans i18nKey = "books.secondbook.description"
  },
  
]

in en.json file description of second book is empty:

"books": {
  "firstbook": {
     "name": "Pippi Longstocking",
     "description": "Pippi Longstocking is the fictional main character."
   }
 "secondbook": {
     "name": "Karlsson on the roof",
     "description": " "
   }

I want to render <div> component for each book only if it has description. I'm trying to do it like this but for secondbook is still rendered.

books.map(b => 
 { 
    b.description && (
    <div> {b.description} </div>
 )}

Can you help me to do this? thank you

CodePudding user response:

The probelm is that the description of the second book is not empty, it has a whitespace. So just add the .trim() function

books.map(b => b.description && b.description.trim() ? <div> {b.description} </div> : null)

I added two checks just in case if description is null or undefined.

CodePudding user response:

instead of

books.map(b => 
 { 
    b.description && (
    <div> {b.description} </div>
 )}

add this

books.map(b => 
 { 
    b.description.props.i18nKey && (
    <div> {b.description} </div>
 )}

CodePudding user response:

It is still rendered because b.description for second object is " " which is a string of length 1 , and so is not empty ,

checking string logic:
empty string => return false
other wise return true .

There are many ways to check if a string is empty , for example :

books.map(b => 
 { 
    (b.description && b.description.trim())  (
    <div> {b.description} </div>
 )}
  • Related