How to place custom route links in Reactjs component


Suppose you have a React application which uses link to navigate another route/page. How do we place the link ? . Let’s look at the post example.

const PostTitles= props=>(
  <div>
    <div>Date: {props.post.createdAt} </div>    
    <a href=`/post/${props.post._id}` >{props.post.title} </a>
  </div>
)

In the above code is a part of blogging web app, which consists of posts,uers,comments and tags components. In PostTitles component which shows title link of posts we used back tick ( `) to add variable. The back tick inside the render part may not work perfectly as in JavaScript.

Solution

So to make it work we have to add pair of extra curly braces ({}) as follows

const PostTitles= props=>(
  <div>
    <div>Date: {props.post.createdAt} </div>    
    <a href={`/post/${props.post._id}`} >{props.post.title} </a>
  </div>
)

Following React posts may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.