156

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?

4 Answers 4

279

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.

Sign up to request clarification or add additional context in comments.

3 Comments

works great, but if you're using a compiler like babel, then template strings are more elegant.
what if its a mailto ?
@tallgirltaadaa: no difference. JSX / JavaScript doesn’t care about the actual value of the string.
107

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

2 Comments

for this to work is it necessary to use ` and not ' ?
Yes the backtick is a new es6 syntax for string interpolation, Updated my answer with a link
12

In addition to Felix's answer,

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

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

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.