Want to render different values at different time in react formik

49 views Asked by At

I want to render a value if my Id is true if the Id is false the value shouldnt exist, is it possible to render what values formik

initialValues={{
                        id:currentBankData.id || '',
                        name: currentBankData.name || '',
                        address: currentBankData.address || '',
                        country: currentBankData.country || '',
                        region: currentBankData.region || '',
                        city: currentBankData.city || '',
                        swiftCode: currentBankData.swiftCode || '',
                        routeCode: currentBankData.routeCode || '',
                        
                        //Example want to do something like this
    if(Id){
        imageBinairyData: currentBankData.image ||'' ,
    }else{
    image: currentBankData.image || '',
    }
                    }}
2

There are 2 answers

3
Paveloosha On BEST ANSWER

Try this

//Example want to do something like this
  [Id ? 'imageBinairyData' : 'image']: currentBankData.image || '',

So your code may look like

initialValues={{
  id:currentBankData.id || '',
  name: currentBankData.name || '',
  address: currentBankData.address || '',
  country: currentBankData.country || '',
  region: currentBankData.region || '',
  city: currentBankData.city || '',
  swiftCode: currentBankData.swiftCode || '',
  routeCode: currentBankData.routeCode || '',
  [Id ? 'imageBinairyData' : 'image']: currentBankData.image || '',
}}
3
Bill On

I suppose you could do something like this:

<Form
  initialValues={{
    id:currentBankData.id || '',
    name: currentBankData.name || '',
    address: currentBankData.address || '',
    country: currentBankData.country || '',
    region: currentBankData.region || '',
    city: currentBankData.city || '',
    swiftCode: currentBankData.swiftCode || '',
    routeCode: currentBankData.routeCode || '',
    imageBinairyData: !Id ? undefined : currentBankData.image || '' ,
    image: Id ? undefined : currentBankData.image || '',
  }}
/>

Or you can simply create the values conditionally before passing in:

render () {
  const initialValues = {
    id:currentBankData.id || '',
    name: currentBankData.name || '',
    address: currentBankData.address || '',
    country: currentBankData.country || '',
    region: currentBankData.region || '',
    city: currentBankData.city || '',
    swiftCode: currentBankData.swiftCode || '',
    routeCode: currentBankData.routeCode || '',
  };
  if (Id) {
    initialValues.imageBinairyData = currentBankData.image || '';
  } else {
    initialValues. image = currentBankData.image || '';
  }

  return <Form initialValues={initialValues} />
}