Home > other >  I just want to output the products in the dashboard, In which the quantity is less than 10. It is co
I just want to output the products in the dashboard, In which the quantity is less than 10. It is co

Time:03-21

{details.map((val, colorMap, prodName) => {

This is where I'm a bit lost with its conditional statement

        if( colorMap < 10 ){
          return ( 
                  <ul>
                    <li key={prodName}><p className="pt-2">{val.prodName} </p></li>
                    <li><p className="pt-2">{}</p></li>
                  </ul>  
          );
        }
        return null;

CodePudding user response:

there seems to be confusion there i guess, instead of destructuring in the map statement you are passing 3 arguments which is making it go wrong...

In the map statement do it this way:

function mapperRender() {
  details.map(({val, colorMap, prodName}) => {
     if( colorMap < 10 ){
          return ( 
                  <ul>
                    <li key={prodName}><p className="pt-2">{val.prodName} </p></li>
                    <li><p className="pt-2">{}</p></li>
                  </ul>  
          );
        }
        return null;
   }
}

and then in the jsx:

<div>
  {mapperRender()}
</div>

CodePudding user response:

Initially you want to filter out those objects that have a colorMap value less that 10, and then you need to map over those filtered elements.

In this example I've added the data to state. I've then filtered the data, and used that data to create the list items.

const { useState } = React;

// Pass in the data
function Example({ data }) {

  // Add the data to state
  const [ state, setState ] = useState(data);

  // `filter` all the objects where the
  // colorMap is less than 10 into a new array
  function getFiltered(data) {
    return data.filter(obj => {
      return obj.colorMap < 10;
    });
  }

  // Return an array of mapped JSX list items
  function createJSX(filtered) {
    return filtered.map(obj => {
      return <li key={obj.val}>{obj.prodName}</li>
    });
  }

  // `filter` the data in state...
  const filtered = getFiltered(state);

  // ...and use that to create the JSX
  return (
    <ul>{createJSX(filtered)}</ul>
  );

}

const data=[{val:1,colorMap:2,prodName:"Shoe"},{val:14,colorMap:14,prodName:"Bobby Davro"},{val:3,colorMap:3,prodName:"House"},{val:34,colorMap:34,prodName:"Barney"}];

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