Home > Back-end >  How to add conditional statement inside react fragment
How to add conditional statement inside react fragment

Time:10-30

Inside of the react fragment I have to add conditional statement. On basis of the conditional statement, return what expected

return (
   <React.Fragment>
      <Toolbar
         pageTitle={i18next.t('TITLE')}
         iconButtons={this.state.icons}
         {this.props.abc && this.props.abc.operation ?(
          moreButton={moreButton}
         ):null}
      />

if this.props.abc.operation is present then only show morebutton if not show only iconbuttons this is my condition and above is the code i tried. any help would be really appreciated.

CodePudding user response:

 <>
  <Toolbar
     pageTitle={i18next.t('TITLE')}
     iconButtons={this.state.icons}
     moreButton={this.props.abc && this.props.abc.operation && moreButton}
  />
</>

Try to use this.

CodePudding user response:

Instead of conditional rendering you can do like below.

isAbcOperationExist = (args) => {
  if(args && args.operation){
    return true;
  }
  return false;
}

Now inside component props:

   <Toolbar
     pageTitle={i18next.t('TITLE')}
     iconButtons={this.state.icons}
     showMoreButton={() => this.isAbcOperationExist(this.props.abc)}
   />

Based on result returned boolean value by method isAbcOperationExist you can show or hide moreButton

More Example:

Assumption this is class based component:

class YourComponent extends React.Component {
   constructor(props){
     super(props)  
   }

   isAbcOperationExist = (args) => {
     if(args && args.operation) {
       return true;
     }
     return false;
   }
              
   render (){
     return (
       <Toolbar
         pageTitle={i18next.t('TITLE')}
         iconButtons={this.state.icons}
         moreButton={moreButton}
         showMoreButton={() => this.isAbcOperationExist(this.props.abc)}
       />
      )
     }
    }

For Toolbar Component assuming it as functional base component:

const Toolbar = ({pageTitle, iconButtons, showMoreButton, moreButton}) => {
  return(
    <div>
      {
        showMoreButton ? <button onClick={moreButton}>Show More</button> : null
      }
    </div>
  )
}
  • Related