How can a child component's height be dynamically adjusted according to its parent's size?

Here is a link to the codesandbox I created: https://codesandbox.io/s/jolly-agnesi-j5bzr?file=/src/App.js

Below is a screenshot of the project:

https://i.sstatic.net/GdYVZ.png

The red background content is dynamically generated, causing the height of the grey card to be dynamic as well.

My goal is to have all components adjust their heights based on the tallest child component in the container. I've set the parent container to grow according to the tallest child and each child component has been given a height of 100%, but they still don't completely fill the container. I'm not sure where the issue lies. Ultimately, all grey cards should have equal heights.

Answer №1

If you're looking for a JavaScript solution, consider adding a ref to your main cards container that can be used later to retrieve the container's height.

<div className="mobile-wrapper" ref={ref => (this.container = ref)}>

Next, save the container's height to a state and then apply it to the style attribute of your card.

const [containerHeight, setContainerHeight] = useState();
    
useEffect(() => {
    setContainerHeight(this.container.clientHeight);
}, []);

Card container:

<div
    key={id}
    className="scroll-shortcuts-item"
    style={{ height: containerHeight }}
>

I've made some CSS adjustments by changing the box-sizing, which affects the inner card's layout within the parent

".scroll-shortcuts-item"
. The cards may look thinner due to this change, so feel free to adjust the min-width accordingly.

height: 100%;
box-sizing: border-box;

Check out the CodeSandBox for implementation details: https://codesandbox.io/s/jolly-benz-kqd26?file=/src/App.js

This approach also works for multiple rows of cards. Just iterate through the cards to find the tallest one in terms of height.

Answer №2

Give this a shot:

// MainApp.js

import React from "react";
import "./styles.css";
import styled from "styled-components";
import ResourceCard from "./ResourceCard";

const StyledShortcutContainer = styled.div`
  .mobile-wrapper {
    margin: 50px 0;
    width: 100%;
    display: flex;
    background-color: blue;
  }

  .scroll-shortcuts-item {
    background-color: yellow;
    flex: 1;
    max-width: 200px;
    margin: 0 10px;
    white-space: pre-line;
  }
`;
const shortcutsList = [
  {
    id: 1,
    title:
      "Example Title",
    subText: "Sample Subtext",
    link: "http://example.com"
  },
  // Additional shortcut items here...
];

export default function MainApp() {
  return (
    <StyledShortcutContainer>
      <div className="mobile-wrapper">
        {shortcutsList.map(
          ({
            id,
            title,
            subText,
            link
          }) => (
            <div key={id} className="scroll-shortcuts-item">
              <ResourceCard
                handleClick={() => {}}
                mainText={title}
                subText={subText}
                color="blue"
                isDesktop={false}
                link={link}
                handleLinkClick={() => {}}
              />
            </div>
          )
        )}
      </div>
    </StyledShortcutContainer>
  );
}

// ResourceCardComponent.js

import React from "react";
import styled from "styled-components";

const StyledCard = styled.div`
  // Styles for the card component
`;

const ResourceCard = ({
  mainText,
  subText,
  color,
  isDesktop,
  link,
  handleLinkClick
}) => {
  return (
      <a
        href={link}
        rel="noopener noreferrer"
        target="_blank"
        style={{ color: "black", textDecoration: "none", width: "100%" }}
      >
        <StyledCard
          onClick={handleLinkClick}
          color={color}
          isDesktop={isDesktop}
        >
          <div className="main-text">{mainText}</div>
          {subText && <div className="sub-container">{subText}</div>}
        </StyledCard>
      </a>
  );
};

export default ResourceCard;

(edit: removed extra 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

Unable to access Redux store (simple Redux example)

Upon visiting , I came across an example that I attempted to replicate: import React from 'react'; import ReactDom from 'React-dom'; import {Redux, bindActionCreators, combineReducers, createStore, applyMiddleware} from 'redux&ap ...

I am attempting to use useSelector to set the initial value for useState, but I am encountering difficulties in making it work

I encountered an issue while trying to retrieve and set my state using useSelector in React. Even though I am able to successfully log the data when using console.log, the value remains empty when attempting to put it into a useState hook. const settings = ...

Adjusting the color of a cell based on its value

Currently, I am in the process of converting a CSV file to an HTML table by utilizing a tool available at . However, I am facing a challenge in modifying the background color of cells based on their values. I would greatly appreciate any help or guidance w ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

Guide to embedding an iframe generated with JavaScript into a React component

I'm currently working on developing an app that will utilize an iframe. The goal is to have controllers in place to adjust the style of the iframe and add text to it, essentially creating a preview function. I've been attempting to use Javascript ...

What is the best way to handle errors in the front-end when receiving responses from expressjs?

Here is the issue that I am facing: //express server app.post('/register', (req, res) => { const { password, passwordConfirm } = req.body; if (password === passwordConfirm) { //... } else { ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...

Show/Hide sections of content that transition and rearrange the layout of the page

I have a layout with 9 squares on a page. When clicking on a square, I want a full-width div to appear underneath it, pushing the other squares down. I've tried following a tutorial to understand the JavaScript behind this functionality, but I'm ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

Unwanted gap appears in the image slider

There seems to be a pesky little gap right below my image slider that I just can't seem to get rid of. I was hoping to spruce it up with a box-shadow, but when I tried it out on jsfiddle, it ended up looking pretty awful because of the annoying gap. I ...

When attempting to transmit data to the server, an error message pops up in the DevTools console of the browser. The error is displayed as "Network Error at create

I am currently utilizing React JS for the front end of my web application and PHP for the back end. When I try to send data to the server upon clicking a button on the webpage, I encounter the following error: Network Error at createError (createError.js:1 ...

Troubleshooting an Issue with CSS Sliding Doors

I'm having trouble getting the right image to show on my website. The left side of the image is fine, but I can't figure out how to make the right one appear. As a HTML/CSS beginner, I'm still learning the basics. For more information, vis ...

Using colored circles in ASP Dropdownlist ListItems (without jQuery): A step-by-step guide

Objective: To create a Dropdown list that displays a green circle if someone's Availability is True, and a red circle if someone's Availability is False. Note: The task needs to be accomplished without the use of jQuery, as it is restricted in t ...

How to use getServerSideProps in Next.js

In my current scenario, I find myself within a folder in the pages directory, specifically in a file named [id].jsx. My goal is to make getServerSideProps return just the name of the page, for example /page/id123 should return id123. import Link from &a ...

Having trouble aligning items within columns using Bootstrap 4?

Even after researching and attempting solutions from previous questions, I still have not been able to achieve the desired outcome. What is the best way to align items inside columns? How can I adjust image size to perfectly fit the column width? <sec ...

Looking for a way to efficiently add multiple value inputs to a JSON object using jQuery or JavaScript?

Here is the HTML input tag code I am working with: <form id="info"> <input id="A" name="A" type="hidden" nodetye="parent" value="A"> <input id="A1" name="A1" type="text" nodetype="child" value="a1val"> <input id="A2" name ...

Implementing Pagination Functionality Using Knockout.js

Sample JSON Data [{ "name": "A Goofy Movie (1995) 720p HDTVRip x264 Eng Subs [Dual Audio] [Hindi DD 2.0 - English DD 2.0] Exclusive By -=!Dr.STAR!=-", "progress": 0, "size": "1.06 GB", "downloaded": "87.98 KB", "hash": "8fe65e43464debe ...

Exporting an HTML table to Excel while excluding any hidden <td> elements

I have a web application with an HTML table that displays data to users. I wanted to export the table to Excel and found a jQuery code for it. However, the exported data includes information that is hidden in the table. Is there a way to export the tabl ...

Dimensions of images in Bootstrap carousel

Hey there! I'm having an issue with the responsiveness of a carousel on my website. The problem is that I have 7 horizontal images (1800x1200) in the carousel, but the last one is vertical and I can't seem to code it properly to make it responsiv ...

What are the functioning principles of older ajax file uploading frameworks (pre-html5)?

Traditional HTML includes an input element with a file type option. Tools are available that enable asynchronous file uploads with progress tracking. From what I gather, this is achieved by splitting the file into chunks and sending multiple requests wit ...