Search code examples
reactjsgatsbyreact-component

Compound Link Destination Using Gatsby Link Via Props


I have a component called Plan that is using the Gatsby Link Component. It looks something like this:

const Plan = props => (
  ...
  <Button>
    <Link to={props.goTo}>Learn More</Link>
  </Button>
  ...
)

This allows me to use the component as follows: <Plan goTo='events' />, which will create the following URL: www.sitename.com/events.

However, what I really want is for each URL to include advertise directory as follows: www.sitename.com/advertise/events. However, I don't want to have to include advertise in the goTo prop.

To get this result, I tried the following:

const Plan = props => (
  ...
  <Button>
    <Link to=`advertise/${props.goTo}`>Learn More</Link>
  </Button>
  ...
)

But this does not work.

So what I am wondering is how can I accomplish this.

Any ideas?

UPDATE:

Just to be clear -- this is how I use the component:

  <Plan goTo="events" />
  <PLan goTo="banner-ads" />

Currently, this leads to the following HTML (with class names stripped out):

<button><a href="/events">Learn More</a></button>
<button><a href="/banner-ads">Learn More</a></button>

What I want is to use the component in the exact same way (<Plan goTo='events' />), but have the HTML be slightly different:

<button><a href="/advertise/events">Learn More</a></button>
<button><a href="/advertise/banner-ads">Learn More</a></button>

[note the addition of /advertise at the beginning of the href attribute]


Solution

  • Wrap your backticks in braces:

    <Link to={/`advertise/${props.goTo}`}>Learn More</Link>
    

    The braces tell JSX that it needs to interpret the contents as JavaScript.

    If you're adding /advertise to every path, consider adding that to your Gatsby path prefix.