React - How to expand an element and hide others, on click

React - How to expand an element and hide others, on click

To implement a functionality where clicking on one element expands it and hides others (accordion-style behavior) in React, you typically manage the state of each element's expanded state. Here's a step-by-step guide on how to achieve this:

Example Implementation

Assume you have a list of items, and you want to expand one item at a time when clicked, collapsing others if they are expanded.

  1. Component Structure

    Create a React component that renders a list of items. Each item can be expanded or collapsed.

    import React, { useState } from 'react'; const Accordion = ({ items }) => { const [expandedId, setExpandedId] = useState(null); const toggleItem = (id) => { if (expandedId === id) { setExpandedId(null); // Collapse if already expanded } else { setExpandedId(id); // Expand clicked item } }; return ( <div className="accordion"> {items.map((item) => ( <div key={item.id} className="accordion-item"> <div className="accordion-header" onClick={() => toggleItem(item.id)}> {item.title} </div> {expandedId === item.id && ( <div className="accordion-content"> {item.content} </div> )} </div> ))} </div> ); }; export default Accordion; 
  2. CSS (Optional)

    You can add CSS styles to control the appearance and transitions of the accordion elements:

    .accordion { width: 100%; } .accordion-item { border: 1px solid #ccc; margin-bottom: 10px; } .accordion-header { background-color: #f0f0f0; padding: 10px; cursor: pointer; } .accordion-content { padding: 10px; background-color: #e0e0e0; } 
  3. Usage Example

    Use the Accordion component in your main application, passing in an array of items to display:

    import React from 'react'; import ReactDOM from 'react-dom'; import Accordion from './Accordion'; const items = [ { id: 1, title: 'Item 1', content: 'Content for Item 1' }, { id: 2, title: 'Item 2', content: 'Content for Item 2' }, { id: 3, title: 'Item 3', content: 'Content for Item 3' }, ]; function App() { return ( <div className="App"> <h1>Accordion Example</h1> <Accordion items={items} /> </div> ); } ReactDOM.render(<App />, document.getElementById('root')); 

Explanation

  • State Management: useState hook is used to manage the expandedId state, which tracks the currently expanded item by its id.
  • Toggle Function: toggleItem function checks if the clicked item is already expanded (expandedId === id) and toggles its state accordingly.
  • Rendering: The Accordion component maps through the items array, rendering each item with a header that, when clicked, toggles its content visibility based on expandedId.

Notes

  • Accessibility: Consider adding ARIA attributes for improved accessibility, especially for screen readers (aria-expanded, role="button", etc.).
  • Performance: For large datasets, optimize rendering and state updates as needed.
  • Customization: Extend the component to support additional features like animations, different styling, or nested accordions.

This approach provides a basic implementation of an accordion component in React where clicking on an item expands it and collapses others, facilitating a user-friendly interface for displaying content interactively.

Examples

  1. How to toggle visibility of a single item in a list using React?

    const App = () => { const [expandedIndex, setExpandedIndex] = useState(null); const items = ['Item 1', 'Item 2', 'Item 3']; const handleToggle = (index) => { setExpandedIndex(expandedIndex === index ? null : index); }; return ( <div> {items.map((item, index) => ( <div key={index}> <h2 onClick={() => handleToggle(index)}>{item}</h2> {expandedIndex === index && <p>Details about {item}</p>} </div> ))} </div> ); }; 

    Description: This example uses state to track which item is expanded, showing details only for the selected item.

  2. How to manage expanded state for multiple elements in React?

    const App = () => { const [expandedItem, setExpandedItem] = useState(null); const handleExpand = (item) => { setExpandedItem(expandedItem === item ? null : item); }; return ( <div> {['Item A', 'Item B', 'Item C'].map(item => ( <div key={item}> <button onClick={() => handleExpand(item)}>{item}</button> {expandedItem === item && <p>Content for {item}</p>} </div> ))} </div> ); }; 

    Description: This implementation manages expanded states for multiple elements using a single state variable to track the currently expanded item.

  3. How to expand and collapse elements using CSS transitions in React?

    const App = () => { const [expandedIndex, setExpandedIndex] = useState(null); const items = ['First', 'Second', 'Third']; const handleToggle = (index) => { setExpandedIndex(expandedIndex === index ? null : index); }; return ( <div> {items.map((item, index) => ( <div key={index}> <h3 onClick={() => handleToggle(index)}>{item}</h3> <div style={{ maxHeight: expandedIndex === index ? '100px' : '0', overflow: 'hidden', transition: 'max-height 0.5s ease' }}> <p>Details for {item}</p> </div> </div> ))} </div> ); }; 

    Description: This example shows how to use CSS transitions to smoothly expand and collapse content based on state.

  4. How to create an accordion component in React?

    const Accordion = ({ items }) => { const [openIndex, setOpenIndex] = useState(null); const toggle = (index) => { setOpenIndex(openIndex === index ? null : index); }; return ( <div> {items.map((item, index) => ( <div key={index}> <h4 onClick={() => toggle(index)}>{item.title}</h4> {openIndex === index && <p>{item.content}</p>} </div> ))} </div> ); }; 

    Description: This component allows you to create an accordion effect, where only one section can be expanded at a time.

  5. How to expand a section and change button text on click in React?

    const App = () => { const [expanded, setExpanded] = useState(false); return ( <div> <button onClick={() => setExpanded(!expanded)}> {expanded ? 'Hide' : 'Show'} Details </button> {expanded && <p>Here are the details...</p>} </div> ); }; 

    Description: This code toggles the display of details and changes the button text based on the expanded state.

  6. How to implement a dynamic list that expands on click in React?

    const DynamicList = () => { const [activeIndex, setActiveIndex] = useState(null); const items = ['Apple', 'Banana', 'Cherry']; return ( <div> {items.map((item, index) => ( <div key={index}> <h2 onClick={() => setActiveIndex(activeIndex === index ? null : index)}> {item} </h2> {activeIndex === index && <p>Details about {item}</p>} </div> ))} </div> ); }; 

    Description: This component allows clicking on list items to expand them and show additional details, maintaining an active index.

  7. How to use React hooks to manage expanded items?

    const ExpandableList = () => { const [expandedItems, setExpandedItems] = useState([]); const toggleItem = (index) => { setExpandedItems(prev => prev.includes(index) ? prev.filter(i => i !== index) : [...prev, index] ); }; return ( <div> {[...Array(5).keys()].map(i => ( <div key={i}> <h3 onClick={() => toggleItem(i)}>Item {i + 1}</h3> {expandedItems.includes(i) && <p>Content for Item {i + 1}</p>} </div> ))} </div> ); }; 

    Description: This code demonstrates how to use an array in state to track multiple expanded items.

  8. How to expand an item and keep others closed with a single state variable?

    const App = () => { const [expandedIndex, setExpandedIndex] = useState(null); const items = ['One', 'Two', 'Three']; const handleClick = (index) => { setExpandedIndex(expandedIndex === index ? null : index); }; return ( <div> {items.map((item, index) => ( <div key={index}> <h2 onClick={() => handleClick(index)}>{item}</h2> {expandedIndex === index && <p>Details of {item}</p>} </div> ))} </div> ); }; 

    Description: This example shows a simple way to keep one item expanded while others are collapsed using a single index in state.

  9. How to animate expanding and collapsing elements in React?

    const AnimatedList = () => { const [expanded, setExpanded] = useState(false); return ( <div> <button onClick={() => setExpanded(!expanded)}>Toggle</button> <div style={{ maxHeight: expanded ? '100px' : '0', overflow: 'hidden', transition: 'max-height 0.3s ease' }}> <p>This is some expandable content!</p> </div> </div> ); }; 

    Description: This implementation animates the expand/collapse transition using inline styles for smooth effects.

  10. How to conditionally render different content based on expanded state?

    const ConditionalRender = () => { const [expanded, setExpanded] = useState(false); return ( <div> <button onClick={() => setExpanded(!expanded)}>Toggle Content</button> {expanded ? ( <p>Expanded content is now visible!</p> ) : ( <p>Click the button to see more.</p> )} </div> ); }; 

    Description: This example shows how to conditionally render different components based on the expanded state, enhancing user interactivity.


More Tags

jsonschema geoserver dynamic-programming credit-card keyword-argument aws-sdk-ruby dispatchworkitem stm32f4discovery control-characters dialect

More Programming Questions

More Chemical thermodynamics Calculators

More Everyday Utility Calculators

More Auto Calculators

More Biology Calculators