javascript – How to create dynamic href in react render function?-ThrowExceptions

Exception or error:

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 (
                    return <li key={}><a href='/posts/'{}>{post.title}</a></li>

How do I do it so that each post has href’s of /posts/1, /posts/2 etc?

How to solve:

Use string concatenation:

href={'/posts/' +}

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.


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


In addition to Felix’s answer,


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


Could you please try this ?

Create another item in post such as then assign the link to it before send post to the render function. = '/posts/+ id.toString();

So, the above render function should be following instead.

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

Leave a Reply

Your email address will not be published. Required fields are marked *