0

I have a column list of elements, and each of them has hidden div, I want to show hidden element on click, but when I'm clicking another div, I want to hide current and show the one I clicked last, how can I do it correctly?

Thomas Rositsky
  • 177
  • 1
  • 3
  • 10
  • Plenty of examples here on SO that do the same, make some HTML markup, try something and then ask if you get stuck with code and snippet. – ikiK Jun 22 '20 at 18:45
  • Does this answer your question? [Show/hide 'div' using JavaScript](https://stackoverflow.com/questions/21070101/show-hide-div-using-javascript) – ikiK Jun 22 '20 at 18:45

2 Answers2

0

You could have two specific classes, one that hides element and one that shows element. when clicking on the element you can use jQuery or JavaScript to toggle the class that shows element for the hidden div of that specific element and hide everything for any other div.

stanlagtan
  • 35
  • 7
0

The component you're rendering could take in an active prop and only render the second div if this prop is true.

With this, you could then keep track of which element is selected in the parent.

I threw together a working example with very simple content

import React, { useState } from 'react';

const ListItem = ({id, isActive, handleClick}) => {
    return (
        <div id={id} onClick={handleClick}>
        Here is the element
            {!!isActive && <div>I am the selected element</div>}
        </div>
    );
};

export const List = () => {
    const [selectedItem, setSelectedItem] = useState();
    const items = ['one', 'two', 'three'];
    
    const handleClick = (event) => {
        setSelectedItem(event.target.id);
    }

    return (
        <div>
            {items.map(item => (
                <ListItem id={item} isActive={item===selectedItem} handleClick={handleClick}/>
            ))}
        </div>
    )
}
Mike Rivet
  • 106
  • 4