Displaying HTML elements conditionally in React depending on boolean values

Developing a component that limits the display of text to the first 40 characters, but can show the full description when a Chevron click event is triggered. The goal is to have the content expand in a similar fashion as it currently does with the Accordion component, increasing its height to fit the additional content. Any advice on how to improve this concept would be greatly appreciated!

// @flow
import styled from "styled-components";
import chevron from "../Assets/chevron-icon.svg";

type Props = { attribute: AttributeType, className?: string };

const Accordion = styled.div`
  background-color: #e5e9eb;
  height: 56px;
  width: 612px;
  border-radius: 2px;
  border: 1px solid #27282a;
  margin-bottom: 48px;
  display: flex;
  align-items: center;

  span {
    padding-left: 24px;
  }
`;

const Chevron = styled.img`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
`;

const ExpandableString = ({ attribute, className }: Props) => {

  const fullDescription = attribute.readonlyvalue;
  const shortHeading = fullDescription.substring(0, 40) + '...';
  let isExpanded = false;

  function toggleContent() {
    isExpanded = true;
  }

  return (
    <Accordion className={className}> 
      <span>{shortHeading}</span>
      <Chevron onClick={toggleContent} src={chevron} alt="Expand or collapse content" />
    </Accordion>
  );
};

export default ExpandableString;

Answer №1

Store your information in the state and switch it on/off

const ExpandableString = ({ property, theme }: Props) => {
  const [isToggled, setIsToggled] = React.useState(false);

  function changeVisibility() {
    setIsToggled(prev => !prev);
  }

  return (
    <Accordion className={theme}> 
      <span>{description}</span>
      <Chevron onClick={changeVisibility} src={arrow} alt="Show or hide content" />
    </Accordion>
  );
};

Subsequently, utilize the isToggled state to decide when to display your React component.

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

How can I resolve the issue of React not identifying the prop on a DOM element?

Currently, I am learning React and facing an issue with a warning message: "react-dom.development.js:86 Warning: React does not recognize the isSelected prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell i ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

Having trouble clicking the button due to the overlay blocking it?

This code contains the HTML portion <li id="nav1" class="navs"><a unselectable="on" draggable="false" class="Navigation" href="http://youtube.com">YouTube</a></li> Below is the CSS code .navs:after { content: ""; position: ab ...

Is it advisable for action creator functions to modify only one field at a time?

Currently, I am diving into the world of redux and find myself a bit perplexed after working through the todos tutorial. The tutorial introduced a simple todo list example consisting of a text field for the todo item and another field that is associated wi ...

Connecting Bootstrap Tabs Dropdown to Website LinksIncorporating Bootstrap Tabs Dropdown Menu

Having an issue with my dropdown list in the Twitter Bootstrap tab - it's not responding when clicked. I've checked Stackoverflow for solutions but nothing has worked so far. I even tried removing the data-toggle='tab' attribute. Just ...

Master the art of building custom ReactJS applications with a targeted focus

Is it possible to develop a react application with a specific range? This method: npx create-react-app web1 generates this package.json: { "name": "web1", ..... } I am interested in understanding how to create it with a particular ...

Challenges encountered when attempting to access files from the filesystem on vercel

Currently, I am working on a website that includes a "blog" section with markdown files. The setup reads the files seamlessly from the file system without any errors... except when deployed on Vercel. In that case, it throws a "No such file or directory" e ...

Start a new redux-saga process when the user logs in and logs out

Currently diving into the world of Redux-Saga and facing a challenge in understanding how to properly connect users to a chat service (specifically Chatkit by Pusher) upon login and disconnect them on logout. At this point, I have an "auth" saga that wait ...

Steps for creating a basic JQuery function for dividing integers

My website constantly updates with real-time data from our PI server, refreshing every 10 seconds. I've been given the task to take two existing data points already on my page and calculate their division, then visualize the new result on a graph. Due ...

Is the PHP variable receiving a null value by the conclusion of the script?

I'm facing a puzzling issue that I just can't crack. Currently, I'm in the process of developing a blog and I've encountered an anomaly with a cookie-generated variable that holds a post ID. Strangely, when I reach the if(isset) stateme ...

Tips for preventing repetition of code in components with varying designs:

How can I avoid repeating code between two components that share some methods but have different layouts? Below are sample components with a method "renderLastItem" that uses prop "something" passed by the parent component. I considered using the Higher ...

Trouble arises with kids when trying to adjust the display to block mode

I need to set all the div elements inside the div with id "editor" to display as block. However, when I change the display property of the div with id "editor", only that specific div's display is affected, while everything else inside the div becomes ...

Turn off the standard caps lock tooltip in Internet Explorer input boxes

When using the login dialog on my password input in Internet Explorer, a default tooltip appears when caps lock is activated (other browsers do not have this feature). I am looking to remove this default tooltip without relying on JavaScript. Is there an a ...

I'm diving into the world of mui for the first time, and I'm encountering an issue when trying to export a component. Instead of importing { DehazeIcon} from "@mui/icons-material", I

My introduction to mui has hit a roadblock - I am unable to export normally. When I try import { DehazeIcon } from "@mui/icons-material";, an error is thrown. Here's my package.json: { "name": "client", "version& ...

What is the best way to assign a unique ID to every <td> element within a table using React Js?

Hello everyone. I am currently working on assigning unique ids to each td in a table based on data received through an API. This is what my code looks like so far. CodeSandbox const assignIdsToTableData = (data) => { var items = Object.values(data)[0 ...

Exploring the power of Next JS by implementing server-side rendering with a

I am faced with the challenge of incorporating navigation into my layout by utilizing data from an API and then displaying it on specific pages. The catch is that the Layout file is not located in the pages folder, meaning I cannot use traditional getStati ...

What is the method for configuring the asp-for input tag helper to create camelCase names?

My view model is structured as follows: public class MyModel{ public DateTime? StartDate {get;set;} } When using an input tag on a view with the asp-for tag helper, the default HTML generated looks like this: <input type="datetime" id="StartD ...

What is the reason for forEach returning an empty array?

I am currently working with an array called getOrdersBySalesman which holds information about orders, such as id, client, and stage. My goal is to filter these orders based on their stage attribute, however, I seem to be encountering an issue where the c ...

Combining arrays that run parallel in Jquery

Seeking a solution similar to looping through multiple arrays in parallel using jQuery, but this time to construct an HTML page. I have three sets of parallel objects with arrays, potentially forming a 2D array. {"images":["Bellevue\/images\/1. ...

Using the ES6 filter method to iterate through a double nested array of objects

Struggling with filtering a nested array of objects and specifically stuck at the filter part. Any idea on how to eliminate one of the marks? this.state = { data: [ { id: 1, name: "Main", subs: [ { id: "jay", ...