Home > OS >  Check for multiple array indexes in react/typescript, whether one exists?
Check for multiple array indexes in react/typescript, whether one exists?

Time:12-29

if(inputData.info[0].instruction){
  return (
  <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ 
    __html: replaceTextLinks(inputData.info[0].instruction) 
    }}>
  </Text>
)
  }
  else {
    return null
  }

So the possible index positions for the inputData.info] index are 0-68. How can I achieve to check whether there exists data for an array index between 0-68, and if it finds one than then to return the if statement with this array index?

CodePudding user response:

Well, what about:

let index = 14;

return inputData.info[index] && inputData.info[index].instruction ?
  <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ 
  __html: replaceTextLinks(inputData.info[index].instruction) 
  }}> :
  null;

CodePudding user response:

inputData.info.find(inf => !!inf) will return the first object that is not null or undefined.

  • Related