Adjusting the width of innerHtml within a React router link to match the parent element's width

My current challenge involves a table where a cell is represented as a link. Within this setup, I am incorporating html content into the text of the link:

<TableCell align="left" classes={{root: classes.cellPadding}}>
  <Link className={classes.link} to="/">
    <HtmlFormattedText html={oppgave.oppgave_tekst}/>
  </Link>
</TableCell>

The HtmlFormattedText function appears as follows:

import React from 'react';
import PropTypes from 'prop-types';
import withStyles from "@material-ui/core/styles/withStyles";

const HtmlFormattedText = ({classes, html, ...rest}) => {
  return (
    <span {...rest} className={`${classes.formattedText} ${classes.root}`} dangerouslySetInnerHTML={{__html: html}}></span>
  );
};

HtmlFormattedText.propTypes = {
  html: PropTypes.string.isRequired
};

const styles = (theme) => ({
  formattedText: {
    '& p': {
      marginBlockStart: 0,
      marginBlockEnd: 0
    }
  },
  root: {
    maxWidth: 200
  }
});

export default withStyles(styles)(HtmlFormattedText);

I am currently grappling with the task of truncating long texts within the htmlInnerText and adding an ellipsis if the content exceeds the width limit of the cell. Despite setting the max-width for both the TableCell and HtmlFormattedText, the desired outcome has not been achieved. For further details, you can refer to the codesandbox demo available here. Any suggestions on how I can successfully implement text truncation with an ellipsis?

Answer №1

When you apply the CSS property text-overflow: ellipsis, it will add an ellipsis to the text. To make this work, be sure to add it to the element that contains the text (in your situation, the <code><p />
tag).

To implement this, try adding the following CSS to your <p/> tag. This should make the ellipsis display.

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Regarding the max-width of table-cell, keep in mind that table-cell may not strictly adhere to the max-width value. Tables and their child elements have their own way of determining width based on their content.

Answer №2

To achieve the desired styling for the paragraph element, you can include the following CSS styles:

formattedText: {
    "& p": {
      display: "block",
      textOverflow: "ellipsis",
      overflow: "hidden",

For a working example, check out the link below. https://codesandbox.io/s/material-demo-chehs

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

Decoding a formatted string

Here is a string that needs parsing: const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");' The goal is to generate a JSON structure like this: [{id: 'a', map: 'b'}, {id: 'foo', map: 'bar&a ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

Retrieve the chosen option from a Select Dropdown and display it in a modal before carrying out the form submission

I need help figuring out how to send a warning message when a "delete" button is clicked on my webpage. I want the message to appear in a modal and display the selected value from a dropdown menu. Here is the code I have so far: <form action="elim ...

Issue with modal dialog not triggering onshow event after postback

In my application, I have a Bootstrap modal dialog that is used to display data when the user clicks on "Edit" in a jQuery data table. The modal contains Cancel and Submit buttons. Everything works correctly when I open the modal, click Cancel, select ano ...

What is the best way to execute a randomly chosen function in JavaScript?

I need help running a random function, but I'm struggling to get it right. Here's what I have so far: <script> function randomFrom(array) { return array[Math.floor(Math.random() * array.length)]; } function randomchords(){ randomFrom ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

Make an angularJS PUT request using $http

After selecting a value from the dropdown selection, I am attempting to make a PUT call in AngularJS. Although I have successfully retrieved the value from the selection, I am encountering difficulty in generating the response for the PUT call. Below is t ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

Change the time format from '18/10/2016 10:31:22PM' to '18/10/2016 22:31:22' in JavaScript

var currentDate = new Date('18/10/2016 10:31:22PM'); var formattedTime = currentDate.toLocaleTimeString(); alert(formattedTime); This code is returning an 'invalid date' output. To fix this issue, I need to convert the date format to ...

Prevent event propagation in jQuery by using .stopPropagation() when hovering over a

When trying to implement event.stopPropagation() in a specific scenario, I encountered an issue with a blinking background image on my submenu. To address this, I added a pseudo-element (background:green) to the parent element by toggling a new class using ...

Using promises and the fetch function to connect to a database

I am attempting to utilize promises with the fetch() function in order to access MongoDB from the front-end, but I am encountering some issues. var Promise = () => ( new Promise((resolve, reject) => { //perform certain actions, make requests ...

How can we use withStyles to customize the styling of a selected ListItem in ReactJS and Material UI?

I am seeking assistance in changing the style of a specific ListItem, similar to what is demonstrated in this Codesandbox. In the Codesandbox example, a global CSS stylesheet is utilized, but I prefer to implement the changes using the withStyle techniqu ...

What issues could potentially arise from utilizing the MIME type application/json?

I'm currently developing a web service that needs to return JSON data. After doing some research, I found recommendations to use application/json. However, I am concerned about potential issues this may cause. Will older browsers like IE6+, Firefox, ...

ReactJS requires HTTP server to transpile babel code before running

I am a beginner when it comes to working with reactjs and I am currently in the process of setting up babel to execute babel code without having to serve HTTP files. Following the instructions on the Package Manager, I have successfully installed it along ...

Utilizing AJAX POST requests from JavaScript to a Rails 4 controller while implementing Strong Parameters

As a newcomer to Rails, I am looking to insert song_id and title received from JavaScript via AJAX POST into a MySQL database. In my JavaScript file: var song_id = "23f4"; var title = "test"; $( document ).ready( function() { jQuery.ajax({ ...

AngularJS Event Handler Fails to Trigger

I'm currently working on a form that I need to submit using the ng-submit event through a custom Auth service. This is a snippet of the login.html (partial template) <div class='container'> <form class='form-signin' ...

Opt for res.render() over res.send() when developing in Node.js

I recently developed an image uploader for ckeditor. After uploading a file, I need to send back an html file that includes the name of the image to the client. Check out the code snippet below: router.post('/upload', function (req, res, next) ...

Remove an item from the options list in the select2 plugin after an event occurs

I am currently using the Select2 plugin in my project and I am facing an issue where I want to remove an option from the main list. However, when I click on the "x" button generated by the code, it only removes it temporarily from the plugin's list. U ...

When viewed on a mobile device, the page defaults to displaying the NumPad instead of the Text Keyboard in Angular

The email field in my angular app is opening a Key Pad in mobile view and I'm not sure why. <form (ngSubmit)="onSubmit()" #emailForm="ngForm"> <div class="emailaddress" style="text-align:center;" *ngIf="!showEmail"& ...

Leveraging UseParams for Detailed Product Pages

I am in the process of developing a product detail page using the useParams Hook in my ReactJS application. Unfortunately, I have encountered some issues as I am able to retrieve the ID from the URL but unable to fetch the item's title, image, and pri ...