Search code examples
javascriptreactjsjsxobject-literal

ReactJS need to conditionally display different onclick vs Link based on logic


Goal I have it to display different HTML with onclick vs. route

Without logic in the Render() const contents = this.state.data.map(item => (

This is the logic I'm struggling with

<button id={item.Member_ID} type="button"
  {` ${this.isExist(item.Member_ID) ? <Link to='surveysai/'>
      <button type="button" className='btn btn-success'>SAI</button>  </Link>             
    : ${onClick={(e) => this.downloadUser(item.Member_ID, e)}}`}
    className={`btn ${this.isExist(item.Member_ID) ? "btn-success" : "btn-warning"}`} > {this.isExist(item.Member_ID) ? "SAI" : "Ready for Download"}</button>

This WORKS from button class:

<button id={item.Member_ID} type="button"
 className={`btn ${this.isExist(item.Member_ID) ? "btn-success" : "btn-warning"}`} > {this.isExist(item.Member_ID) ? "SAI" : "Ready for Download"}</button>   

Below is OLD code BEFORE changing to conditional , below is not code i want , for reference only.

onclick

<button id={item.Member_ID} type="button" onClick={(e) => this.downloadUser(item.Member_ID,e)} 
      className={() => this.checkItem(item.Member_ID)}>Ready for Download</button>

Link route redirect

<Link to='surveysai/'>
    <button type="button" className="btn btn-success">SAI</button>                   
</Link>

Solution

  • Why don't you conditionally render either the Link or the button.

    {this.isExist(item.Member_ID) ? (
      <Link to='surveysai/'>
          <button type="button" className='btn btn-success'>SAI</button>  
      </Link>
    ) : (
      <button 
        onClick={(e) => this.downloadUser(item.Member_ID, e)}
        className={`btn ${this.isExist(item.Member_ID) ? "btn-success" : "btn-warning"}`}> {this.isExist(item.Member_ID) ? "SAI" : "Ready for Download"} . 
      </button>
    )}
    

    Also, you don't actually need to render a button inside of a Link, assuming this is a React Router Link component. You can just pass classnames as props like:

    <Link to="/wherever" className="btn btn-success" />