Home > Back-end >  reactjs : map the name a only when true
reactjs : map the name a only when true

Time:10-04

[![enter image description here][1]][1]i am tring to show the subModule.subModuleName only if subModule.completed == "true"

{predefined.map((personData, index) => {
        return (
          <thead>
            <tr>
              <th style={styles.th}>{personData.mainModule}</th>
            </tr>
            {personData.sub_module.map((subModule) => {
              return (
                <>
                  <tr>
                    <td style={styles.td}>
                      {subModule.subModuleName && subModule.completed == "true"}
                    </td>
                  </tr>
                </>
              );
            })}
          </thead>
        );
      })}

sub_module is an inner array so i want to show only when completed is true





CodePudding user response:

Solution: Using Array.filter(e => e.completed == "true") before using Array.map.

{predefined.map((personData, index) => {
        return (
          <thead>
            <tr>
              <th style={styles.th}>{personData.mainModule}</th>
            </tr>
            {personData.sub_module.filter(e => e.completed == "true").map((subModule) => {
              return (
                <>
                  <tr>
                    <td style={styles.td}>
                      {subModule.subModuleName}
                    </td>
                  </tr>
                </>
              );
            })}
          </thead>
        );
      })}

And please notice about e.completed == "true" condition, maybe it should e.completed == true. I just guess so because I don't have your input array.

CodePudding user response:

While one way is to add a filter before mapping, you can alternatively conditionally return your render content, and return a <React.Fragment/> when the condition fails. so that would be

personData.sub_module.map((subModule) => {
              if(submodule.completed==="true"){
                return(<React.Fragment/>)
              else{
                return (
                  <>
                    <tr>
                      <td style={styles.td}>
                        {subModule.subModuleName && subModule.completed == "true"}
                      </td>
                    </tr>
                  </>
                );
              }
            })}

This approach is more efficient compared to the filter approach because you iterate over personData.sub_module only once, where the filter approach involves two iterations(one during filter, and one during map).

  • Related