skip to Main Content

Hi all,

I’m trying to create a link in ReactJS, passing a search string. What I want to create is

<td><Link to={{pathname: '/select_item', search: '?item_id=83'}}>Select</Link></td>

where the item id (in this example, 83) is replaced with the variable "itemId", which varies in a loop. If I hard code the itemId, as in the example above, then the link works.

I tried

<td><Link to={{pathname: '/select_item'0, search: '?item_id=`${itemId}`'}}>Select</Link></td>

but that doesn’t work – the itemId isn’t replaced, so the link text is

/select_item?item_id=${itemId}

I then tried

var path = "pathname: '/approve_item1', search: '?walk_id=" + item.id + "'";
<td><Link to={{path}}>Select</Link></td>

but that doesn’t work either.

I hope that makes sense! Can anyone let me into the secret as to how to insert a variable into an interpolation string?

Thanks,

Graeme

2

Answers


  1. You should be wrapping the entire string in backticks.

    <td><Link to={{pathname: '/select_item', search: `?item_id=${itemId}`}}>Select</Link></td>
    

    More info on template strings: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

    Login or Signup to reply.
  2. I think You could do that using String Interpolation like this:

    <td><Link to=`/select_item?item_id=${itemID}`>Select</Link></td>
    

    Check this for more explanation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#string_interpolation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search