How to create dynamic href in react render function?

JavascriptReactjs

Javascript Problem Overview


I am rendering a list of posts. For each post I would like to render an anchor tag with the post id as part of the href string.

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 do I do it so that each post has href's of /posts/1, /posts/2 etc?

Javascript Solutions


Solution 1 - Javascript

Use string concatenation:

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

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

Solution 2 - Javascript

You can use ES6 backtick syntax too

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

More info on es6 template literals

Solution 3 - Javascript

In addition to Felix's answer,

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

would work well too. This is nice because it's all in one string.

Solution 4 - Javascript

Could you please try this ?

Create another item in post such as post.link then assign the link to it before send post to the render function.

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

So, the above render function should be following instead.

return <li key={post.id}><a href={post.link}>{post.title}</a></li>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionConnor LeechView Question on Stackoverflow
Solution 1 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 2 - JavascriptNathView Answer on Stackoverflow
Solution 3 - JavascriptthalackerView Answer on Stackoverflow
Solution 4 - JavascriptKhachornchit SongsaenView Answer on Stackoverflow