React components are losing their styling when using array.map() function

I have an array of objects.

Within my React Component, I've written a block of HTML code:

    <div class="item">
      <div class="card card--big">
        <div class="card__cover">
          <img src="img/covers/cover2.jpg" alt="" />
          <a href="#" class="card__play">
            <i class="icon ion-ios-play"></i>
          </a>
        </div>
        <div class="card__content">
          <h3 class="card__title"><a href="#">Benched</a></h3>
          <span class="card__category">
            <a href="#">Comedy</a>
          </span>
          <span class="card__rate"><i class="icon ion-ios-star"></i>7.1</span>
        </div>
      </div>
    </div>

If I manually paste it - everything works great, but if I use Array.map, the styles are lost (the card size is incorrect).

  const elements = content.map((content, index) => {
    return (
      <div class="item">
        <div class="card card--big">
          <div class="card__cover">
            <img src="img/covers/cover2.jpg" alt="" />
            <a href="#" class="card__play">
              <i class="icon ion-ios-play"></i>
            </a>
          </div>
          <div class="card__content">
            <h3 class="card__title"><a href="#">Benched</a></h3>
            <span class="card__category">
              <a href="#">Comedy</a>
            </span>
            <span class="card__rate"><i class="icon ion-ios-star"></i>7.1</span>
          </div>
        </div>
      </div>
    );
  });

How can I fix this issue?

Answer №1

I tested the card HTML markup within a jsFiddle environment to observe any changes in card sizes. The result was as expected, with no anomalies detected. You can view the code snippet here.

function CardList() {
  var content = [
  { id: 1, name: 'card 1' },
    { id: 2, name: 'card 2' },
    { id: 3, name: 'card 3' },
  ];
  
  return (
    <div className="wrapper">
      {content.map((item, index) => (
        <div className="item">
          <div className="card card--big">
            <div className="card__cover">
              <img src="img/covers/cover2.jpg" alt="" />
              <a href="#" className="card__play">
                <i className="icon ion-ios-play" />
                {item.name}
              </a>
            </div>
            <div className="card__content">
              <h3 className="card__title"><a href="#">Benched</a></h3>
              <span className="card__category">
                <a href="#">Comedy</a>
              </span>
              <span className="card__rate"><i className="icon ion-ios-star" />7.1</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

ReactDOM.render(<CardList />, document.querySelector("#app"));
.wrapper {
  display: flex;  
}

.item {
  margin: 1rem;
}

.card {
  padding: .5rem;
  background-color: #21D4FD;
}

.card.card--big {
  padding: 2rem;
}
<div id="app"></div>

Answer №2

The issue originates from the preceding parent element that precedes the .item class. It is essential to properly style the parent element. For example, if the parent div has a class name of .container, you can set its height to 100vh and then adjust the item's height to 80% for uniformity. Another solution could be applying display: flex to the parent element if the width is causing issues.

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

Unable to modify the fill color of SVG elements through iteration

I'm looking to update the fill color of SVG elements by comparing their ids with an array in React. I've successfully looped through all available elements, compared their ids with the data in the array, and generated the correct results. However ...

Tips on customizing the appearance of a Fluent UI checkbox

I am having trouble styling the Fluent UI checkbox and changing the checkmark color when it is in an indeterminate state. I am using Flueint UI 8.x. "dependencies": { "react": "16.8.6", "@fluentui/react": & ...

React app experiencing freezing due to custom asynchronous function utilisation

I am currently facing an issue with my personal project where the application freezes under certain circumstances. The initial load works fine, but when I make changes to the code causing React to re-render, the app just freezes. It seems to be related to ...

The controller returned a null value

I've encountered a situation where I'm utilizing a service file to execute a stored procedure: function createCampaign($campaignName, $groupNumber){ $stmt = \DB::connection('odbc')->getPdo()->prepare('CALL SCHE ...

Exploring object properties to access JSON arrays

Consider this scenario with a JSON file: { "shows": [ { "name": "House of cards", "rating": 8 }, { "name": "Breaking bad", "rating": 10 } ] ...

Troubleshooting the Problem with CSS Margin in HTML Footer

I'm encountering an issue with the footer on my website. The margin: auto; command doesn't seem to be working for the list items in the footer. I want the items in the footer to occupy one-third of the width, but no matter where I place the marg ...

Fetching JSON data from a URL using Node.js and Express

I am currently working on retrieving a Json object from a URL using Express: Below is the code I have written: app.get('/device/:id', (req, res, next) => { console.log('device: ' + req.params.id + ' Request received&apos ...

Making changes to a specific row in a datatable within a Flask project

I need help with creating an edit function for my data table. I only require front-end and a bit of JS (Ajax) code to send the data. The picture below shows what I am trying to achieve: https://i.sstatic.net/9QDXl.png Here is how my data table looks like: ...

Sending ecommerce data to Google Analytics in React can be a daunting task

I'm facing a challenge in sending enhanced eCommerce tracking data to Google Analytics using React. For testing purposes, I inserted the following code in my index.js: ReactGA.initialize('UA-MY-ID-7', { debug: true, }); ReactGA.plugi ...

Is it possible to run nightwatch.js tests on a Linux machine?

Struggling to kick off the nightwatch automated UI tests on a Linux machine running CentOS OS? Starting is proving to be quite challenging. This is the test_settings configuration in my nightwatch.json: "test_settings": { "default": { ...

The error message "Unable to map props.theTodos" is displayed

I'm facing an error message while compiling: "TypeError: props.theTodos.map is not a function". I've been struggling with this issue for quite some time, but I haven't found a solution yet as I'm using hooks instead of class components. ...

Best practice for sending intricate variables to JavaScript via HTML

Steering away from PHP's htmlentities, I made a change in my code: <?php echo '<img ... onclick="MP.view(\''.$i->name.'\') />'; ?> However, I decided to go a different route by JSON encoding the ...

Determining the dimensions of static alerts in bootstrap

I am currently working on creating a web page using Twitter Bootstrap that includes a "floating" (fixed-position) alert at the top. Here is an example of how I have set it up: HTML: <div class="container"> <div class="row"> <div clas ...

Is there a way to verify if text was generated using CSS?

I am working with the following HTML structure: <h4 id="myModalLabel"></h4> In my CSS, I have set the content dynamically using the following code: #myModalLabel::after { content: "gebeurtenis"; } For a live example, you can check out t ...

Preserve the edited screenshot once it has been captured

I am looking to incorporate a feature in my application that allows users to capture the current screen, annotate it (edit/scribble, etc.), and then send it via email. My app is built using phonegap and primarily uses javascript/jquery for functionality on ...

Retrieve files from a Webservice and transfer them to Azure Blob Storage using Node.js and Express framework

In order to provide users with their own separate workspace, I am working on retrieving files from a vendor's Web service and storing them in unique blob containers. This way, users can edit the files without interfering with each other's work. I ...

What is the best method for encrypting a URL that contains AngularJS data?

Here is the URL that needs to be encrypted: <a class="btn btn-success btn-sm btn-block" href="@Url.Action("myAction", "myController")?Id={{repeat.Id}}&HistoryId={{repeat.HistoryId}}" ng-cloak>View History</a> I am seeking guidance on enc ...

Tomickigrzegorz Script Finder Predictive Search

Hey there, I recently tried out the autocomplete script created by tomickigrzegorz. Check it out here! It's been working smoothly for me, but I'm facing an issue with external link tags like https//google.com not functioning properly. Here is ...

Crafting a personalized arrow for sorting headers in Angular Material

Currently working on an Angular 5 project and I'm looking to implement a custom sort icon in the header. The goal is to achieve a similar effect to this example, without using the default arrow. I attempted to modify the CSS styles, but it wasn' ...

Integrating FlaskWTF with Vue frontend: sharing CSRF tokens securely

I'm currently developing an application that combines a Vue frontend with a Flask backend. While I am creating forms in Vue, I am looking to enhance security using FlaskWTF for CSRF/XSRF protection and form validation on the backend. To implement th ...