Menu

gitpiper

Collapse react Code Snippet in 2024

componentschildrenstatebeginner

Last Updated: 16 December 2024

Renders a component with collapsible content.

  • Use the useState() hook to create the isCollapsed state variable. Give it an initial value of collapsed.
  • Use the <button> to change the component's isCollapsed state and the content of the component, passed down via children.
  • Use isCollapsed to determine the appearance of the content and apply the appropriate className.
  • Update the value of the aria-expanded attribute based on isCollapsed to make the component accessible.
.collapse-button { display: block; width: 100%; } .collapse-content.collapsed { display: none; } .collapsed-content.expanded { display: block; }
const Collapse = ({ collapsed, children }) => { const [isCollapsed, setIsCollapsed] = React.useState(collapsed); return ( <> <button className="collapse-button" onClick={() => setIsCollapsed(!isCollapsed)} > {isCollapsed ? 'Show' : 'Hide'} content </button> <div className={`collapse-content ${isCollapsed ? 'collapsed' : 'expanded'}`} aria-expanded={isCollapsed} > {children} </div> </> ); };
ReactDOM.render( <Collapse> <h1>This is a collapse</h1> <p>Hello world!</p> </Collapse>, document.getElementById('root') );

react snippet similar to Collapse For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️