Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic href in react render function?

People also ask

How do you add dynamic href in React?

To create dynamic href in React component, we can use template strings. <a href={`/customer/${item. _id}`}> {item. get("firstName")} {item.

How do you make a dynamic href in HTML?

getElementById('someDiv'); // create <a> tag var tag = document. createElement(a); // set the href attribute tag. setAttribute('href', exampleHref); // append the node to the parent div. appendChild(tag);

How do you add links in React JS?

To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.


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.


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,

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

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