简体   繁体   中英

React conditionally show link if there is content on json file?

Did some searching around, but could not find anything. this is something simple on jQuery and Rails, but not sure if there is a correct way to to this in React. I have this component that is grabbing its data form a JSON file, and I want to only display a certain link if the JSON has content, otherwise I want to hide it. I tried this way so far with no luck:

  renderList(projectLinks){ //let self = this; return projectLinks.map(function(link) { var showDemo = ""; if(link.urlDemo === ""){ console.log("i'm empty"); showDemo = "displayNone"; } return <Panel header={link.title} eventKey={link.eventKey} key={link.title}> <p>{link.description}</p> <img src={link.image} className="img-thumbnail" alt="project thumbnail"/><br /> <a href={link.urlDemo} className={showDemo}>Demo </a> <a href={link.urlCode}>Code </a> </Panel> }); } 

so, if the json link is empty like this: "urlDemo": "", I want the link to be hidden.

Appreciate the help.

Inside render, use conditional operator. Here's an example

render(){
   return (
      <div>
          {this.state.check ? <div>Show this if check is true</div> :
              <div>Show this if check is false</div>}
      <div>
   )
}

Edit: A more specific example

render(){
   return(
      <div>
         {link.urlDemo ? <a href={link.urlDemo}>Demo </a> : null}
      </div>
   )
} 

Another way of doing the same:

render(){
   return(
      <div>
         {link.urlDemo && <a href={link.urlDemo}>Demo </a>}
      </div>
   )
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM