How to create dynamic href in react render function?

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?

Answers 1

  • 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.


Related Articles