Tom Rudge
Tom Rudge

Reputation: 3272

Don't pass value to component if string equals "" empty

I'm passing values to my component but some have a value of "". This creates a visual container which is empty on my view. I need the value not to pass at all if it equals "".

<AddIntel initialValues={{
    pastIntelNotes: [
    profile.intelNotes,
    profile.intelNotes2,
    profile.intelNotes3,
    profile.intelNotes4
]
}} />

I've tried a conditional

<AddIntel initialValues={{
    pastIntelNotes: [
    profile.intelNotes,
    profile.intelNotes2 != "" ? profile.intelNotes2 : null,
    profile.intelNotes3,
    profile.intelNotes4
]
}} />

null is being past to the component which still maps it as a length

initialValues:
   pastIntelNotes: Array(4)
     0: "Notes"
     1: null
     2: "Notes2"
     3: "Notes3"
length: 4

I am looking for this:

initialValues:
  pastIntelNotes: Array(3)
     0: "Notes"
     1: "Notes2"
     2: "Notes3"
length: 3

Upvotes: 0

Views: 79

Answers (2)

hindmost
hindmost

Reputation: 7195

Use Array's filter to remove unwanted values from array:

initialValues.filter((v) => v !== '').map(..)

Upvotes: 1

sdabrutas
sdabrutas

Reputation: 1517

Try this:

const pastIntelNotes = [profile.intelNotes, profile.intelNotes2, profile.intelNotes3, profile.intelNotes4];

<AddIntel initialValues={{
   pastIntelNotes: pastIntelNotes.filter(note => note !== ""),
}} />

Upvotes: 1

Related Questions