Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

javascript - Reveal component only on the clicked element

I have a group of rendered items: enter image description here

I want to attach a dropdown on each of a single element when I click on that 3 dots in a toggling form. But when I click on one of the components I get it revealed on all elements:

enter image description here

This is a component that is rendered:

const ClassItem = ({
  id,
  ...
  name,

}) => {
 ...

  return (
    <>
      <div id={id} className={`class-pill${attending ? ' attending' : ''}`}>
        <p className='class-name subtitles bold'>{name}</p>
        <div className='date-time'>
          <p className='body regular'>{date}</p>
          <p className='body regular'>{time}</p>
        </div>
        <p className='teacher-name body regular'>{teacher}</p>
        <div className='icon-type'>
          {showStatus()}
          <p className='body regular'>{status}</p>
        </div>
        {edit && (
          <button
            id={id}
            onClick={onClick}
            className='icon-more-vertical'
          ></button>
        )}
      </div>
    </>
  );
};

And this is the component where is rendered:

....
  const openBubble = (event) => {
    console.log('ID', event.target);
    displayBubble(!bubble);
  };

  const Bubble = ({ display }) => {
    return (
      <div className={`bubble ${display ? 'display' : 'hide'}`}>
        EDIT, CANCEL
      </div>
    );
  };
...
 return (
              <>
                <ClassItem
                  id={item.classId}
                  key={item.classId}
                  edit={editClass}
                  attending={isAttending}
                  name={item.className}
                  date={moment(item.datetime).format('MMMM Do YYYY')}
                  time={moment(item.datetime).format('LT')}
                  teacher={teacherName}
                  status={item?.status}
                  onClick={() => openBubble(item)}
                />
                <Bubble display={bubble} />
              </>
            );
          })}

...

What is wrong with this implementation?

question from:https://stackoverflow.com/questions/66054821/reveal-component-only-on-the-clicked-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the attached code snippet it seems like you are sharing the same state across all items. I would suggest to try a simple

const [closed, setClosed] = useState(false)

inside the ClassItem component in order to keep the state of the Bubble


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...