Search code examples
javascriptarraysreactjsmappinggatsby

Mapping an array with two different styles = odd array with one style and even array in other style


This is the standard mapping for blog posts in Gatsby and they show all the blog posts with a title, the date, and the post.

const { blogs } = data.strapi
const { id } = data.strapi.blogs
  return (
    <Layout>
      <article>
        <header>
          <h1> {blogs.title} </h1>
          <p> {blog.description} </p>
        </header>
        <hr />
      </article>
    </Layout>
  )
};

export default BlogPost;

but how can I change the look that appears in the first blog post with the font to the right and color red; the second blog post title to the left and the color blue and so on?

I made an if conditional but I can't make it work


let even=blogs.filter((a,i)=>i%2===1); // 1 3 5
let odd = blogs.filter((a,i)=>i%2===0); // 0 2 4

          <div>
            {even.map((blog, i) => {
              return <h1 className="text-danger">{blog.title}</h1>
              })}
          </div>

// Output : title[0], title[2], title[4]; all red

//Expected Output: title[0] (red), title[1] (blue), title[2] (red), title[3] (blue) title[4] (red), title[5] (blue);


Solution

  • Assuming you're using CSS to style your blog, you can just conditionally add the class name to style each element at the same time you loop through them to print it.

    <div>
      {blogs.map((blog, i) => {
        return (
          <h1 className={`text-danger ${i % 2 === 1 ? "isEven" : "isOdd"}`}>
            {blog.title}
          </h1>
        );
      })}
    </div>