Conditionally Use Gatsby Link in React Compoment

北慕城南 提交于 2019-12-11 12:52:09

问题


I have a react component that contains within it a number of sub-components. I want to wrap those sub-components in an anchor tag. Now, sometimes that anchor tag will link to a sub-page, other times it will link to an external page.

Now, I'm Gatsby and that means whether or not I use an <a> tag or a <Link> component depends on whether or not I'm linking to an internal page (<Link>) or an external page (<a>). See here for more details: https://www.gatsbyjs.org/docs/gatsby-link/

Now, I thought that I could accomplish this by checking whether or not I used some custom designed props -- like this:

export const ListItem = props => (
  <div>
    {props.goTo && <Link to={props.goTo}>}
    {props.linkTo && <a href={props.linkTo}>}

        <SubcompomentOne>...</SubcompomentOne>
        <SubcompomentTwo>...</SubcompomentTwo>

    {props.linkTo && </a> }
    {prpos.goTo && </Link> }
  </div>
)

The idea is that if I am use the linkTo prop then I'll use an <a> tag. If I use a goTo prop, then I'll use a <Link> component. And if I don't use either -- then I'll just render the rest of the sub-components without either the <Link> or <a> tag.

That, at least, is how I would like it to work - but something isn't working properly.

So, I am wondering, is there a way to conditionally use the <Link> or <a> tags depending on whether or not the link is internal or external? If so, any ideas how?

Thanks.


回答1:


Opening the jsx tag like (Link and a in your case) and hoping to close it at a different place is not possible in this way. The way you have written is similar to may templating language on server side to render things inside other tags.

In your case you may make use of a different approach. One the approach would be as below.

First assign all your children(like SubcompomentOne, SubcompomentTwo) to a variable. use React.Fragment if you have multiple child.

const children = (<React.Fragment>
    <SubcompomentOne>...</SubcompomentOne>
    <SubcompomentTwo>...</SubcompomentTwo>
  </React.Fragment>
);

Then you may determine which tag to render and the children inside them, similar to below

return (<div>
 {
  props.goTo ?
   (<Link to={props.goTo}>{children}</Link>) : 
   (<a href={props.linkTo}>{children}</a>)
 }
 </div>);



来源:https://stackoverflow.com/questions/56530862/conditionally-use-gatsby-link-in-react-compoment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!