How to create a dynamic href function in a render reaction?

I am making a list of posts. For each message, I would like to make the anchor tag the message identifier as part of the href line.

render: function(){ return ( <ul> { this.props.posts.map(function(post){ return <li key={post.id}><a href='/posts/'{post.id}>{post.title}</a></li> }) } </ul> ); 

How to do this so that each post has href from /posts/1 , /posts/2 , etc.?

+90
javascript reactjs
Jul 22 '15 at 15:35
source share
4 answers

Use string concatenation:

 href={'/posts/' + post.id} 

JSX syntax allows the use of strings or expressions ({...}) as values. You cannot mix both. Inside an expression, you can, as the name suggests, use any JavaScript expression to calculate the value.

+162
Jul 22 '15 at 15:39
source share

You can also use ES6 backlink syntax

 <a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a> 

Learn more about es6 template templates.

+84
Dec 23 '15 at 11:21
source share

Could you try it?

Create another element in the message, for example post.link , then assign a link to it before sending post to the rendering function.

 post.link = '/posts/+ id.toString(); 

So, instead, the following rendering function should be performed.

 return <li key={post.id}><a href={post.link}>{post.title}</a></li> 
0
Nov 19 '17 at 13:06 on
source share

In addition to Felix’s answer,

 href={'/posts/${posts.id}'} 

also suitable. This is good because it is all on one line.

0
Sep 22 '19 at 15:43
source share



All Articles