Display hidden text upon clicking using React Material UI Typography

I have a situation where I need to display text in Typography rows, but if the text is too long to fit into 2 rows, ellipsis are displayed at the end. However, I would like to show the full text when the user clicks on the element. I am attempting to change the CSS attributes onClick (not sure if this can be done in React). Here is what I have so far:

main.tsx

import './style.css'

style.css

Typography[m="2"] {
    overflow-x: hidden !important;
    overflow-y: hidden !important;
}
Typography[m="all"] {
    overflow-x: unset !important;
    overflow-y: auto !important;
}

/*[class="2"] {*/ 
/*overflow-x: hidden !important;*/
/*overflow-y: hidden !important;*/
/*}*/
/*[class="all"] {*/
/*overflow-x: unset !important;*/
/*overflow-y: auto !important;*/
/*}*/

Form.tsx

const [expanded, setExpanded] = useState(false);

const handleToggle = () => {
    setExpanded(!expanded);
};

<Typography onClick={handleToggle}
    sx={{
        display: '-webkit-box',
        overflow: 'hidden',
        WebkitBoxOrient: 'vertical',
        WebkitLineClamp: 2,
        fontSize: "smaller",
        }}
    className={expanded ? "all" : "2"}       //trying to change css attribute by className / m value
    m={expanded ? "all" : "2"}>
    <b>"comment":</b> {longText}
</Typography>

I can see that there is a change in the CSS class onClick (in developer console), however, the class attributes themselves won't change. The classes (css-mzggb7 and css-yfc04t) are probably generated during build because they are not in the project structure. So the changes are not being read from my style.css file. Can you please let me know if I am heading in the right direction or if I should try a different approach? Thank you.

Edit: My next attempt was as follows (unfortunately without success):

const [rowNumber, setRowNumber] = useState<string>("2")

const handleToggle = () => {
    setExpanded(!expanded);
    if(rowNumber == "2") {
        setRowNumber("0");
    } else {
        setRowNumber("2");
    }
};

<Typography onClick={handleToggle}
    sx={{
        display: '-webkit-box',
        overflow: 'hidden',
        WebkitBoxOrient: 'vertical',
        WebkitLineClamp: '{rowNumber}',
        fontSize: "smaller",
        }}">
    <b>"comment":</b> {longText}
</Typography>

Answer №1

Consider using

const HiddenTextClickExpand = () => {

const [toggleText, setToggleText] = useState(true);
const textContent = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";

return (
    <Box width={"40vw"}>
        <Typography
            sx={
                toggleText &&
                {
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    display: "-webkit-box",
                    WebkitLineClamp: "2",
                    WebkitBoxOrient: "vertical",
                }
            }
            onClick={() => setToggleText(prevState => !prevState)}
        >
            {textContent}
        </Typography>
    </Box>
);

};

export default HiddenTextClickExpand;

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

Tips for continuing to write to the same CSV file without starting over

Currently, I am utilizing a nodejs package to write data to a CSV file every minute. The initial creation of the file and the first write operation work fine. However, when attempting to write to the same file again, I encounter an error in nodejs. Despite ...

Does the require function in nodejs have any connection to the package.json file?

If 'random_module' is included in the list of dependencies in my package.json file, can I use the code var rm = require("random_module"); to access it? Essentially, does the argument for require function apply to any module listed under the depen ...

Restricting Horizontal Scrolling in Dash DataTable with multi-tiered header (without any additional empty gaps)

I'm currently developing a Dash application using Plotly that showcases two tables, specifically dash_table.DataTable, each with multiple columns. The initial table features a multi-level header. For both tables, the first few columns are fixed while ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

Align the content of a collapsed bootstrap row vertically

In a row, I have two columns, each containing their own row. When the page width hits the 'xs' break-point, the left column's row will stack its columns on top of each other. The right column is taller than the left column, which leaves a l ...

The power of Ng-show and filtering

What I am aiming for is to display a complete list of cities as soon as the page is loaded. Once a user clicks on a checkbox next to a city, my goal is to utilize ng-show/ng-hide in order to display the results specific to that city while hiding those of ...

Trouble Connecting Local Database with PG NPM Package

I'm encountering issues with using the pg package on my computer. I've attempted to execute the following code: var pg = require('pg'); var con_string = "postgres://user:password@localhost:5432/documentation"; var client = new pg.Clie ...

Create a filter system using a MERN stack that incorporates regex, a search box,

In an effort to understand how the MERN stack operates as a cohesive unit, I have taken on a hands-on approach by following tutorials from bezcoder. These include guides on Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code). Sam ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...

span element causing border-spacing problem

Is there a way to adjust the spacing between these borders? I've tried using border-spacing but it doesn't seem to be working. {{#each spacing}} <span class='space'> {{business}} ({{Count}}) </span> {{/each}} CSS .spac ...

Although the state's value remains the same, a React functional component may still re-render once

Recently, I have become a fan of the React Functional Component and have been experimenting with it. However, I encountered an unusual case that left me puzzled. In my project, I created a custom-hook named "useAutoIncrement" which utilizes a setInterval ...

Adjusting the width of the final card in the deck grid

Currently, I am utilizing angular-deckgrid for image display purposes. Within a container, there are two columns in which images are displayed with the column-1-2 class according to the documentation. However, in certain scenarios where only one image is p ...

Creating Image Overlays with Hover Effects using CSS and PHP Conditions

Looking for some assistance with a Minecraft server listing page I am working on for a client. I have never done this before and have encountered a roadblock. Take a look at this image (apologies for using Paint, I was in a hurry!) The goal is to have the ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...

Displaying the votes through an advanced system called Ajax voting system

I've encountered a challenge while using an ajax voting system in my project. The issue is that I'm utilizing a div with an id to showcase the votes, but whenever someone clicks on vote up or down in any of the posts (which are generated through ...

Could the quantity of JavaScript files impact the performance of a project and cause any delays?

In my current HTML and JavaScript project, I am incorporating multiple JavaScript files. I'm curious to learn about the potential impact of having numerous JavaScript files on a web project's efficiency and speed. Can anyone shed some light on th ...

What is the best way to upload custom fonts in a next.js application during its production phase?

Alright, so here's a question that might seem simple at first glance, but I've already combed through the next.js documentation and can't seem to find a solution. In my next.js project, I'm facing an issue that seems to be either a bug ...

Is there a way to create a reusable HTTP response handler for Node.js applications?

As I work on creating a rest api for a node application, I often find myself repeating the same code structure: function(req, res, next) { databaseCall() .then( (results) => { if (results != null) { res.status(200).send(results); } el ...

When working with Vue 3, remember that inject() function is only allowed within setup or functional components

I'm puzzled as to why I keep encountering this error. I am attempting to utilize the Vuex store in a composition function, but for some reason, it keeps throwing an error regarding inject (even though I'm not using inject at all). My application ...

Enhance User Experience with a Customized Progress Bar using Google Apps Script

I created a Google Sheets cell counter in Apps Script and need help setting up the bootstrap progress bar using the "percentage" variable. GS function cellCounter() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); var ...