Collapsible text in react

Collapsible text in React

If you want to create collapsible content on your React website or application, there are a few different approaches you can take. Here are a couple of options:

Using the useState Hook

One way to create collapsible text in React is to use the useState hook to toggle the visibility of the content. Here's an example:


import React, { useState } from 'react';

function CollapsibleText(props) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setIsOpen(!isOpen)}>
        {isOpen ? 'Hide' : 'Show'}
      </button>
      {isOpen && <p>{props.text}</p>}
    </div>
  );
}

export default CollapsibleText;

In this example, we define a functional component called CollapsibleText that takes a single prop called text. We use the useState hook to create a piece of state called isOpen that starts out as false. When the user clicks the button, we toggle the value of isOpen by calling setIsOpen with the opposite value (i.e. true if it was false and vice versa). We then conditionally render the content inside a paragraph tag based on whether isOpen is true or false.

Using CSS Animations

Another way to create collapsible text in React is to use CSS animations to transition the height of the content. Here's an example:


import React, { useState } from 'react';
import './CollapsibleText.css';

function CollapsibleText(props) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setIsOpen(!isOpen)}>
        {isOpen ? 'Hide' : 'Show'}
      </button>
      <p className={`collapse ${isOpen ? 'open' : ''}`}>
        {props.text}
      </p>
    </div>
  );
}

export default CollapsibleText;

In this example, we define a functional component called CollapsibleText that takes a single prop called text. We use the useState hook to create a piece of state called isOpen that starts out as false. When the user clicks the button, we toggle the value of isOpen by calling setIsOpen with the opposite value (i.e. true if it was false and vice versa). We then render the content inside a paragraph tag with a class of "collapse". We also conditionally add a class of "open" if isOpen is true. In our CSS file, we define a transition for the height of the paragraph tag, so that it smoothly animates open and closed based on the CSS class applied to it.

Overall, there are many ways to create collapsible text in React, depending on your specific needs and preferences. These are just a couple of examples to get you started!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe