Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment:

https://codesandbox.io/s/modest-mclean-utqn3e?file=/src/App.js

My goal is for the first 3 columns to expand when the screen size increases:

cellStyle: {
    fontStyle: "bold",
    whiteSpace: "nowrap",
    textOverflow: "ellipsis",
    overflow: "hidden",
    textAlign: "center",
    width: "15%"
  }

However, I am facing an issue where the width property set in cellStyle does not seem to be taking effect.

Currently, all columns are displaying with equal widths. How can I adjust the width of the first 3 columns to make them bigger?

https://i.sstatic.net/8O6Jf.png

Answer №1

Great job on the styles! Just a reminder to set width: 15% for the correlated headers. Tables need consistent row widths, so make sure all rows have the same width.

For more details, check out this sandbox

import React, { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Box, TextField, Button, Tooltip } from "@material-ui/core";
import plans from "./data";
const useStyles = makeStyles((theme) => ({
  cellStyle: {
    fontStyle: "bold",
    whiteSpace: "nowrap",
    textOverflow: "ellipsis",
    overflow: "hidden",
    textAlign: "center",
    width: "15%"
  },
  headerStyle: {
    width: "15%"
  }
}));
export default function App() {
  const classes = useStyles();

  return (
    <Box>
      <table
        className="table table-striped table-bordered table-sm table-hover"
        style={{ width: "100%", tableLayout: "fixed" }}
      >
        <thead className="thead-dark">
          <tr style={{ textAlign: "center" }}>
            <th className={classes.headerStyle}>Industry</th>
            <th className={classes.headerStyle}>Sponsor</th>
            <th className={classes.headerStyle}>Name</th>
            <th>Compl. Risk</th>
            <th>Plan Util</th>
            <th>ROR</th>
            <th>Expense Ratio</th>
            <th>Retire Rediness</th>
            <th>Cohort</th>
            <th>Overall Grade</th>
            <th>Industry Grade</th>
            <th>Bookmark</th>
          </tr>
        </thead>
        <tbody className="table-hover">
          {plans.map((el, id) => (
            <tr key={el.PlanName + id}>
              <Tooltip title={el.Industry}>
                <td className={classes.cellStyle}>{el.Industry} </td>
              </Tooltip>
              <Tooltip title={el.PlanSponsor}>
                <td className={classes.cellStyle}>{el.PlanSponsor}</td>
              </Tooltip>
              <Tooltip title={el.PlanName}>
                <td className={classes.cellStyle}>{el.PlanName}</td>
              </Tooltip>
              <td>{el.OverallComplRisks}</td>
              <td>{el.OverallPlanUtil}</td>
              <td>{el.OverallROR}</td>
              <td>{el.OverallExpenseRatio}</td>
              <td>{el.OverallRetireReadiness}</td>
              <td>{el.Cohort}</td>
              <td>{el.OverallGrade}</td>
              <td>{el.IndustryGrade}</td>
              <td>{el.IsBookmarked}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Box>
  );
}

Answer №2

Perhaps utilizing the HTML5 colSpan feature to incorporate the required width?

...
...
return (
    <Box>
      <table
        className="table table-striped table-bordered table-sm table-hover"
        style={{ width: "100%", tableLayout: "fixed" }}
      >
        <thead className="thead-dark">
          <tr style={{ textAlign: "center" }}>
            <th colSpan="2">Industry</th>
            <th colSpan="2">Sponsor</th>
            <th colSpan="2">Name</th>
            <th colSpan="1">Compl. Risk</th>
            <th colSpan="1">Plan Util</th>
            <th colSpan="1">ROR</th>
            <th colSpan="1">Expense Ratio</th>
            <th colSpan="1">Retire Rediness</th>
            <th colSpan="1">Cohort</th>
            <th colSpan="1">Overall Grade</th>
            <th colSpan="1">Industry Grade</th>
            <th colSpan="1">Bookmark</th>
          </tr>
        </thead>
        <tbody className="table-hover">
          {plans.map((el, id) => (
            <tr key={el.PlanName + id}>
              <Tooltip title={el.Industry}>
                <td colSpan="2" className={classes.cellStyle}>
                  {el.Industry}{" "}
                </td>
              </Tooltip>
              <Tooltip title={el.PlanSponsor}>
                <td colSpan="2" className={classes.cellStyle}>
                  {el.PlanSponsor}
                </td>
              </Tooltip>
              <Tooltip title={el.PlanName}>
                <td colSpan="2" className={classes.cellStyle}>
                  {el.PlanName}
                </td>
              </Tooltip>
              <td colSpan="1">{el.OverallComplRisks}</td>
              <td colSpan="1">{el.OverallPlanUtil}</td>
              <td colSpan="1">{el.OverallROR}</td>
              <td colSpan="1">{el.OverallExpenseRatio}</td>
              <td colSpan="1">{el.OverallRetireReadiness}</td>
              <td colSpan="1">{el.Cohort}</td>
              <td colSpan="1">{el.OverallGrade}</td>
              <td colSpan="1">{el.IndustryGrade}</td>
              <td colSpan="1">{el.IsBookmarked}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Box>
  );

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

Encoding a two-dimensional array into JSON format

In my PHP script, I am querying a database and formatting the results as JSON: $query = mysql_query($sql); $rows = mysql_num_rows($query); $data['course_num']=$rows; $data['course_data'] = array(); while ($fetch = mysql_fetch_assoc($q ...

The Tab component's onClick event is nonfunctional

I am currently utilizing the Tab feature from the material-ui library in my React project. As I try to come up with a workaround for an issue I am facing, I notice that my onClick event listener is not being triggered. An example of one of the tabs: < ...

In what ways can I leverage the functionalities of an AngularJS directive to delay the display of content until a user clicks on it?

Our rental application utilizes an API call to populate an array, triggering an ngRepeat and generating a list of divs displaying basic rental property information. Upon clicking a specific property, another API call is made to populate an interior ngRepe ...

Find the index of the element that was clicked by utilizing pure JavaScript

I am struggling to find the index of the element that was clicked. Can anyone help me with this? for (i = 0; i < document.getElementById('my_div').children.length; i++) { document.getElementById('my_div').children[i].onclick = f ...

SCRIPT438: The operation failed because the object does not have the ability to use the 'forEach' property or method

Issue with IE8: Property or method 'forEach' not supported $('.tabs').tabs(); $('#search-consumables [data-ajax-call]').change(function() { var $this = $(this), settings = $this.data(), $target = $(setti ...

What is the best way to iterate through an array containing multiple objects in order to create a graph?

My API response contains multiple objects organized in an array: [{"symbol":"AAPL","date":"2020-02-27","adj_close":68.24}, {"symbol":"TSLA","date":"2020-02-27","adj_close":133.8}, {"symbol":"TSLA","date":"2020-02-28","adj_close":122.3}, {"symbol":"AAPL" ...

Utilize React to iterate through data retrieved from firebase

I'm currently facing an issue with Google Firebase Realtime database where I am unable to create an array of the collection. Whenever I loop through the const return in console log, I receive messages as individual objects. However, what I actually n ...

Enhancing Promises.all with extra parameters

Looking to dive into promises, eager to learn. Here is an array of shopIds I'm working with: let shopIdsArray = ['shop1','shop2','shop3']; Additionally, there's an external promise call: getProducts(shopId, ' ...

Arranging data in a table using PHP

After some thorough research, I am finally prepared to dive into the world of PHP. My project involves an HTML5 animation with table sorting functionalities - one button for sorting by date and another for sorting by title. Despite my efforts to find a cus ...

What is the best way to display an input label or placeholder label consistently?

I am currently utilizing the multi-select feature with checkboxes provided by Material UI v4. By default, the settings display an array of 'SELECTED' values using the renderValue={selected => selected.join(', ') function. However, I ...

Building an expandable vertical dropdown with Bootstrap that opens with a click

My goal is to design a vertical menu that expands when clicked, revealing 3 links for each item. I currently have the following setup: This is the initial layout: After clicking all items: The code I've implemented so far looks like this: <!DOC ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

Is there a way to create a dropdown menu that transforms into a burger icon on smaller screens, while still housing all of my navigation items within it?

I'm currently working on a segment of my header that includes a navbar with 3 links, as well as a dropdown menu listing additional functionalities. Here is the current code I have: <div class="col-md-4 pt-4"> <nav class="navbar ...

Looking for answers to a question about Handlebars in Node.js? Click on the following link to explore more

After successfully parsing my Shopify product items into a MongoDB database using a model, I am attempting to display them to the user using the express-handlebars package. However, I've encountered a small issue. I'm utilizing <td><a ...

Managing the hovering of a mouse over an image within an isometric grid displayed on a

I have implemented an isometric grid in HTML canvas. My goal is to handle mouse hover events on the buildings within the grid. Some buildings will vary in heights. In the image below, you can see that when hovering over a tile, the highlighted area shif ...

JavaScript not redirecting to HTML page as expected

I have developed a basic login page that makes an Ajax request to the backend. However, I am experiencing difficulties with redirecting the page upon successful login. The redirect function only seems to work 1 in 15 times, and I'm unsure of the reaso ...

Explain the process of data binding with DOM elements

I'm intrigued by how jQuery has the ability to link arbitrary data with any DOM element without the use of HTML data attributes. $('#div_id').data('suffix', (count++)); In the Firebug HTML snapshot, I don't see any data attr ...

Angular directive: inability to pass ng-repeat item through isolate scope

I am currently working on a directive that has an isolate scope. The template of the directive includes an ng-repeat on an element, along with the following code snippet: ng-click="selection(item)" Within the directive's scope definition, I have spe ...

Encountered an issue while attempting to write to SQLite, error code 6 is

I'm working on a project that involves writing to a SQLite Database from a cross-platform app built with AngularJS, Monaca, and Onsen UI. Within my app, there's a view where users input their username and password. I store these details in a Ser ...

What is the reason behind the immediate firing of the animate callback function when a CSS transition is present?

I am facing an issue where the callback function fires immediately, disregarding the linear ease type and defaulting to the swing ease in CSS transitions. Is there a way to ensure that the animate function works correctly with the transition? The reason fo ...