skip to Main Content

I only want to show the <div> if tax: true in any of the cartItem‘s. tax is a prop inside of productDetails which comes from cartItem:

enter image description here

    const Content = (props) => { 

    let cartItem = props.cartItem;

        {cartItem.indexOf(props.productDetails?.tax) > -1 && (
            <div>
                Show if Tax
            </div>
          )}

    };
    export default Content;

2

Answers


  1. The condition in the code you provided is checking if the value of props.productDetails.tax exists in the cartItem array. However, if you want to show the <div> only if tax: true in any of the cartItem productDetails, you need to check the tax value of each productDetails object in the cartItem array.

    You can do this using the Array.some() method, which returns true if at least one element in the array satisfies the condition specified in the callback function.

    const Content = (props) => {
      let cartItem = props.cartItem;
    
      if (cartItem.some((item) => item.productDetails?.tax === true)) {
        return (
          <div>
            Show if Tax
          </div>
        );
      } else {
        return null;
      }
    };
    
    export default Content;
    

    If you’re still confused then I want you to provide the data of props and productDetails

    Login or Signup to reply.
    1. Cart Item is an array so you will have multiple cartItems there need to loop each and display div for all cartItems which hax a tax

      const Content = (props) => { 
       let cartItem = props.cartItem;
       return (
       {cartItem.filter(p=>p?.tax).map(d => (
              <div>
                  Show if Tax
              </div>
            )))}
       };
       export default Content;
      
    2. f you need to show div if any of the cartItem have a tax

      const Content = (props) => { 
      
        let cartItem = props.cartItem;
        return (
        {cartItem.findIndex(p=>p?.productDetails?.tax) !== -1 ?
           <div>
               Show if Tax
           </div>
        : <></> )}
      };
       export default Content
      

    ;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search