When attempting to perform conditional rendering in React using a stateless functional component, I encounter an error stating "Unexpected token, expected ,"

Here is the code snippet:

'use strict'

import React from 'react'
import { connect } from 'react-redux'
import { Panel, Col, Row, Well, Button } from 'react-bootstrap'

const Cart = ({ cart }) => {

  const cartItemsList = cart.map(cartArr => (
    <Panel key={cartArr.id}>
      <Row>
        <Col xs={12} sm={4}>
          <h6>{cartArr.title}</h6>
        </Col>
      </Row>
    </Panel>
  ));

  return (
    { cart[0] &&
      (<Panel header="Cart" bsStyle="primary">
        {cartItemsList}
      </Panel>)
    }
    { !cart[0] &&
      (<div></div>)
    }
    // {
    //   cart[0] ? (<Panel header="cart" bsStyle="primary">{cartItemsList}</Panel>) : (<div></div>);
    // }
  )
}

const mapStateToProps = state => ({
  cart: state.cart.cart
})

export default connect(mapStateToProps)(Cart)

The issue I am facing is related to conditional rendering. Whenever I try to render cartItemsList within a Bootstrap panel only when cart is not an empty array, I encounter the error "Unexpected token, expected ,". The alternative approach in the commented-out code also triggers the same error. If I remove the condition and directly render the panel with cartItemsList, everything works fine. It's only when adding the condition that the error arises. Can you help me understand why this error occurs?

Answer №1

{} is not necessary for incorporating JS expressions within JSX. Here's how you can write it without using {}:

return (
    cart && cart.length ?
        <Panel header="Cart" bsStyle="primary">
            {cartItemsList}
        </Panel>
    :
        <div>
        </div>
)

An alternative way to write the same code is:

if(cart && cart.length)
    return(
        <Panel header="Cart" bsStyle="primary">
            {cartItemsList}
        </Panel>
    )
return(
    <div>
    </div>
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

TurboRepo initiates the web server and promptly closes down without any issues

I have a turbo-repo set up using pnpm, and I am attempting to launch the React frontend for one of my clients with the following command: npx turbo run start --filter=testclient When executing this command, the output is as follows: • Packages in scope: ...

Is there a way to conceal JavaScript code?

I am trying to keep my AJAX code hidden from users who view the source of my PHP page. How can I achieve this? Below is the AJAX code that I currently have: <script type="text/javascript"> function Ajax(){ var xmlHttp; try{ xmlHttp=n ...

Trigger an event upon completion of a write operation in AngularJS

I want to trigger a search after my user finishes typing (without hitting enter) in AngularJS. Here is a simplified version of my HTML: <div ng-class="input-append" ng-controller="searchControl"> <input type="text" ng-model="ajaxSearch" ng-cha ...

Using Percentage-Based Margin in React-Native

I've encountered a problem in my React Native project where using a percentage value for the margin style attribute seems to shrink the height of one of my View components. However, if I switch to using an absolute value, the issue disappears and ever ...

Set up a personalized React component library with Material-UI integration by installing it as a private NPM package

I have been attempting to install the "Material-UI" library into my own private component library, which is an NPM package built with TypeScript. I have customized some of the MUI components and imported them into another application from my package. Howe ...

Stopping an endless loop when retrieving data from localStorage in next.js

While working with fetching data from localStorage in the useEffect Hook, I encountered an interesting behavior. When I set the dependency array to [] (blank), the data is fetched successfully but new data is not retrieved until the page is refreshed. Howe ...

I am interested in checking the dates of the current date and disabling the button if the date falls within that range

I am attempting to deactivate a button if the current date falls within a three-month period. Despite my efforts to use a combination of Php and JavaScript, I was unable to make it work. PHP Code @php($found = false) @foreach($doctors as $doctor) ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

Ways to verify whether a string has already been hashed in Node.js utilizing crypto

I am currently working on an application that allows users to change their passwords. For this project, I am utilizing Node.js along with the mongoose and crypto libraries. To generate hashes for the passwords, I have implemented a hook into the model&ap ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

When does an xmlHttpRequest object parse serialized XML into a DOM during its lifecycle?

When a JavaScript code with xmlHttpRequest.responseXML() runs, it creates a DOM Document object from the XML-structured HTTP response body. Have you ever wondered at what moment the XML string is turned into the DOM Document by an xmlHttpRequest object? ...

The required and defaultValue attributes seem to be malfunctioning on my Textfield, although the placeholder feature is functioning properly

In the card below, I have implemented a simple edit functionality. Upon clicking edit, a textfield is supposed to appear for me to make changes and save them. However, I am facing issues with the required and defaultValue attributes in my Textfield, alth ...

Troubleshooting Issues with Passing Values in jQuery AJAX POST Requests

Currently, I am working on two basic PHP pages: notification.php <html> <head><title></title> <meta charset="UTF-8"> <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script src="ht ...

Range slider position not being updated after user interaction

I am working on a webpage with an embedded video and a range slider that serves as a progress bar. Using Javascript, I update the value of the range slider as the video plays, allowing users to navigate through the video content. However, I have encounter ...

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...

Error Alert: jQuery Ajax Not Executing

Looking to send form data to PHP using jQuery. Check out the code below. -------------HTML FORM-------------- <div id="createQuestionBlock"> <form id="createQuestionForm" action="" method="POST"> Question Code: <input id="code" ...

JavaScript tabs that smoothly fade in and out

I'm currently working on implementing tabbed content, but I'm struggling with getting the fade effect to apply to the content itself when clicked, rather than just the tab headers. Check out my demo here $('#tab-wrapper li:first').add ...

What is the best way to transfer the search query to a table filter when working with multiple JavaScript files?

I am struggling with passing the search query from my search file to my table file. The data for my datagrid table is retrieved from a database using an API call, and the table code is in one file while the search functionality code is in another file. I h ...

The setting of the custom user agent in the Chrome Extension Manifest Version 3 is not functioning correctly

We currently have an extension that consists of only two files: manifest.json and background.js Despite the browser (Chrome version 112) not reporting any errors, we are facing an issue where the user agent is not being set to 'my-custom-user-agent&a ...