Home > OS >  How to I output an item value inside an anchor tag
How to I output an item value inside an anchor tag

Time:10-03

The data fetched from the API is stored in GetBlogState. In the data there is a key for Slug. I would like to output that key value inside an anchor tag so that it built a link for that specific blog post e.g. /blog/test-1. The following is what I'm currently working with.

   GetBlogState.map((item, index) => (
      <div className="h-68" key={index}>
        ..
        <h2 className="font-bold mb-5 text-xl"><a href="/blog/{item.Slug}" className="hover:underline">{ item.Title }</a></h2>
        ..
      </div>
    ))

CodePudding user response:

In js you can use template strings to inject variables directly inside the string like below. The template strings are done using backticks, the character to the left of the 1 key on your keyboard and then ${} around the variable name:

   GetBlogState.map((item, index) => (
      <div className="h-68" key={index}>
        ..
        <h2 className="font-bold mb-5 text-xl"><a href=`/blog/${item.Slug}` className="hover:underline">{ item.Title }</a></h2>
        ..
      </div>
    ))

CodePudding user response:

use literal templates (backtick).

<h2 className="font-bold mb-5 text-xl"><a href={`/blog/${item.Slug}`} className="hover:underline">{ item.Title }</a></h2>

CodePudding user response:

Use template literals inside curly braces.

<h2 className="font-bold mb-5 text-xl"><a href={`/blog/${item.Slug}`} className="hover:underline">{ item.Title }</a></h2>
  • Related