Home > other >  How to show the value from an if statement inside a foreach loop in react js?
How to show the value from an if statement inside a foreach loop in react js?

Time:05-02

hello i am using react js, any advice and suggestions are hugely appreciated here. The sharedfields forEach loop does console.log the sharedFieldAlias value, if I console.log it outside of the loop it will not output the value. I need the sharedFieldAlias value to display in the span tag but it gives a reference error that sharedFieldAlias is not defined. How can I display the value in the span tag?

sharedfields.forEach((sharedField) => {
        let sharedFieldAlias = sharedField.alias;
        if(value.shared_field_uuid == sharedField.uuid) {
          console.log(sharedFieldAlias);
        }
      });
      
      const fullLabel = (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <InputLabel label={display_name} help={parameter.help?.header_id} />
          {!isLinked ? (
            <LinkOutlined onClick={linkField} style={{ color: blue.primary }} />
          ) : (
            <div>
              <CloseSquareOutlined
                onClick={unlinkField}
                style={{ color: yellow[7] }}
              />
              <span className="ant-typography ant-typography-secondary" id="sharedFieldAlias" style={{ marginLeft: '5px', color: '#262626'}}>
                {sharedFieldAlias}
              </span>
            </div>
          )}
        </div>
      );

CodePudding user response:

Declare the variable sharedFieldAlias outside the loop (just above the loop in your case).

let sharedFieldAlias;
<your loop goes here>

CodePudding user response:

You have to declare the variable outside the loop. It might also help to use a for loop instead of forEach so you can break out of the loop once the value is found.

let sharedFieldAlias;
for (const sharedField of sharedfields) {
  if (value.shared_field_uuid == sharedField.uuid) {
    sharedFieldAlias = sharedField.alias;
    console.log(sharedFieldAlias);
    break;
  }
}

CodePudding user response:

There's no need for a global variable. Use find to check the array, find an object where the uuids match, and return the alias, otherwise return 'None'.

const sharedFields = [
  { alias: 'Bob', uuid: '1' },
  { alias: 'Carol', uuid: '2' },
  { alias: 'Sam', uuid: '3' },
  { alias: 'Moses', uuid: '4' }  
];

function getAlias(fields, uuid) {
  const found = fields.find(field => {
    return uuid === field.uuid;
  });
  return found ? found.alias : 'None';
}

console.log(getAlias(sharedFields, '3'));
console.log(getAlias(sharedFields, '31'));
console.log(getAlias(sharedFields, '2'));

Here's a small working example in React.

function getAlias(fields, uuid) {
  const found = fields.find(field => {
    return uuid === field.uuid;
  });
  return found ? found.alias : 'None';
}

function Example({ data }) {

  return (
    <div>
      <div>{getAlias(data, '3')}</div>
      <div>{getAlias(data, '31')}</div>
      <div>{getAlias(data, '2')}</div>
    </div>
  );

}

const data = [
  { alias: 'Bob', uuid: '1' },
  { alias: 'Carol', uuid: '2' },
  { alias: 'Sam', uuid: '3' },
  { alias: 'Moses', uuid: '4' }  
];

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related