0

I'm using react and i want to map a component only when all my conditions are true, but there are 4 conditions and i don't want to use nested if statements

I tried this and it works, but i just think is ugly and not a good practice:

{posts.map((post, i) => {
              if (
                post.author &&
                post.story_title &&
                post.story_url &&
                post.created_at
              ) {
                return <Card key={i} post={post} />;
              } else {
                return null;
              }

I also tried this and it seems to work, but i'm not sure because when i log the variable isValidPost i get a date and not a boolean false or true:

 {posts.map((post, i) => {
              let isValidPost =
                post.author &&
                post.story_title &&
                post.story_url &&
                post.created_at;
              console.log(isValidPost);
              if (isValidPost) {
                return <Card key={i} post={post} />;
              } else {
                return null;
              }

is there a better way to make this validation?

ludinj
  • 107
  • 7
  • 1
    Your first snippet looks just fine to me. Maybe if you had more properties you'd want something like `Object.values(post).every(Boolean)`, or iterate over an array of required properties and do the same sort of check – CertainPerformance May 11 '22 at 06:36
  • You could filter the result first and then map through it. `posts.filter(post => post.author && post.story_title && post.story_url && post.created_at).map((post, i) => ...)` – Sajeeb Ahamed May 11 '22 at 06:39
  • posts.map((post, i) => { let isValidPost = post.author && post.story_title && post.story_url && post.created_at; return isValidPost ? : null; }); – Aneesh May 11 '22 at 06:40

0 Answers0