JSX: dynamically include element based on condition

I am currently utilizing Bootstrap 3 and I have a requirement to clear each .row once 12 columns have been generated. However, my code is not working as expected and I encounter this error:

Failed to compile. Error in ./src/File/file.js Syntax error: Unexpected token, expected , (145:56)

The issue lies on this line:

{ index % 4 == 0 && <div className="row"> }

const TweetImageList = ({images, removeImage}) => {
    return (
        <div className="TweetImageList">

            <ReactCSSTransitionGroup transitionName="tweetImageTransition"
                                     transitionEnterTimeout={500}
                                     transitionLeaveTimeout={500}>
                {
                    images.map((image, index) => {
                        let column =
                            <div key={index} className="col-xs-3 tweet-image-wrapper">
                                <TweetImage
                                    image={image}
                                    removeImage={removeImage}
                                />
                            </div>;

                        return column;

                    })
                }
            </ReactCSSTransitionGroup>

        </div>
    );
};

It is indeed necessary to clear the row sometimes because it does not automatically clear itself as implied in the BS documentation. For more information, refer to this link:

!! UPDATE !!

I have revised my jsx based on Yo Wakita's suggestion. Floats are now cleared with rows. However, transitions are no longer functioning properly... Any suggestions??????

const TweetImageList = ({images, removeImage}) => {
    return (
        <div className="TweetImageList">

            {
                _.chunk(images, 4).map((chunk, i) => {
                    return (
                        <div key={i} className="row spacing-bottom">

                            {
                                chunk.map((image, j) => {
                                    return (
                                        <div key={j} className="col-xs-3">

                                            <ReactCSSTransitionGroup transitionName="tweetImageTransition"
                                                                     transitionEnterTimeout={500}
                                                                     transitionLeaveTimeout={500}>
                                                <TweetImage
                                                    image={image}
                                                    removeImage={removeImage}/>
                                            </ReactCSSTransitionGroup>
                                        </div>
                                    )
                                })
                            }

                        </div>
                    )
                })
            }
        </div>
    );
};

removeImage()

removeImage(id) {
    this.setState({
        images: this.state.images.filter(function (img) {
            return img.id !== id;
        }),
        startValue: this.state.startValue + this.numPhotoChars
    });
}

Answer №1

To improve the code, consider implementing it as a ternary operation. If index%4 === 0, display the row wrapped element. Otherwise, show the div without the row.

{this.state.photos.map((image, index) => {
  const column =
    <div className="col-xs-3">
      <TweetImage 
        image={image} 
        index={index} 
        key={'image-' + index} 
        removeImage={this.removeImage}
      />
    </div>;
  return (
    index%12 === 0 
    ? <div className="row">
        {column}
      </div>
    : {column}
  );
  }
)}

Edit: Following your suggestion in the comment, it seems like chunking this.state.photos into arrays of length 4 could be beneficial. In case you use lodash, utilize the chunk function in this manner:

  {_.chunk(this.state.photos, 4).map((chunk, i) => 
    <div className="col-xs-3">
      {chunk.map((image, j) => 
        <TweetImage 
          image={image} 
          index={j} 
          key={'image-' + i + '-' + j} 
          removeImage={this.removeImage}
        />
      )}
    </div>
  )}

If you do not use a utility library, you can create a custom function to partition your this.state.photos. Check out examples on this Stack Overflow thread.

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

How can we stop the Bootstrap carousel from pausing when the mouse hovers over it and keep it cycling automatically?

Is there a way to stop the Bootstrap carousel from pausing when hovering with the mouse and instead have it continue cycling through items automatically? I've tried changing the pause argument from "hover" as mentioned in the documentation, but when ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

React component allowing for the reuse of avatars

As a novice in React, I've encountered a challenge. My goal is to develop a simple reusable component using MUI. Specifically, I aim to create an avatar component that can be easily customized with different images when called upon. I want the flexibi ...

Troubleshooting issues with AngularJS's minDate functionality

I have been trying to set the minDate for the datepicker to today, following the example on the angularJS bootstrap site. However, it seems like something is not working correctly. There are no console errors showing up, but it appears that the minDate is ...

What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class comp ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

Adjust the height setting of the React-Highcharts viewport

My initial configuration for highcharts looks like this:- function getInitialHighChartsConfig(chartType) { return { credits: false, chart: { type: chartType, height: 325, }, title: { text: '', useHTML: tr ...

The height of the Material UI Paper component is not appropriately matched with the parent component

I am currently working with the Paper component that contains a Card component, and I am trying to make its height fill the entire screen. To simplify the problem, I have provided the following code: import React from "react"; import { makeStyles ...

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

Displaying dates in Material UI datepicker is not working

My current setup involves using Material UI v14.4 with React, and I have encountered an issue with the DatePicker component not displaying the dates correctly as shown in the attached screenshot. Strangely, there are no visible error messages either. Any s ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

Customizing AngularJS directives by setting CSS classes, including a default option if none are specified

I have designed a custom directive that generates an "upload button". This button is styled with bootstrap button CSS as shown below: <div class="btn btn-primary btn-upload" ng-click="openModal()"> <i class="fa fa-upload"></i> Upload & ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet: const rootElement = document.getElementById('root'); ReactDOM.render( <ThemeProvider theme="MyThemes.default& ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...