Display a hoverable button for a singular element within an array during the process of mapping through the array

const ChatWidget = () => {
const bodyRef = useRef(null)
const [{messages,roomMessages,roomID,socket,user}, dispatch] = useStateValue()
const [dropdown, setDropdown] = useState(false)
useEffect(()=>{
    const setScreen = () =>{
        bodyRef.current.scrollTop = bodyRef.current.scrollHeight
    }

    setScreen()
},[])
const updateMessages = (message) =>{
    const allMessages = messages
    allMessages.push(message)
    dispatch({
        type: "SET_MESSAGES",
        item: allMessages
    })
    bodyRef.current.scrollTop = bodyRef.current.scrollHeight
}
useEffect(() => {
    socket.on('new-message', (message) =>{
        if(messages === null){
            console.log('here it was null')
        } else {
            updateMessages(message)
        }
    })
    // clean up socket on unmount

}, [])
const handleDropdown = (index) =>{
    setDropdown(true)
    console.log(index)
    if(dropdown === true){
        setDropdown(false)
    }
}
return (
        <div className={'chat'}>
            <ChatHeader/>
            <div ref={bodyRef}  className={'chat__body'}>
                {messages?.map((item,index)=>(
                    <Emojify  key={item._id}>
                        <div
                            onMouseEnter={() => handleDropdown(index)}                                 
                            onMouseLeave={handleDropdown}
                            className={`chat__message ${item.name === user.displayName && "chat__reciever"}`}>
                            <h5  className={'chat__messageUser'}>
                                {item.name}
                            </h5>
                            <p className={'chat__messagetext'}>
                                {item.message}
                            </p>
                            {dropdown && <Button><ArrowDropDownIcon/></Button>}
                            {item.img && <img alt={''} className={'chat__img'} src={item.imgURL}/>}
                        </div>
                    </Emojify>
                    ))}
            </div>
            <div className={'chat__footer'}>
                <ChatFooter/>
            </div>
        </div>

);

I am looking to display the Button component

{dropdown && <Button><ArrowDropDownIcon/></Button>}
only when a specific div is hovered over, rather than being rendered for all mapped divs. Any suggestions on how I can achieve this using the index passed in as a parameter?

If you have any ideas or solutions, please let me know. Thank you!

Answer №1

Instead of using a single "global" boolean to track whether the dropdown is open or closed (which all mapped elements are referencing), you can associate a specific dropdown that you want to be open. It's great that you already have an index passed to the handler.

Modify the state to store either null (no dropdown) or an index (show dropdown).

const [dropdown, setDropdown] = useState(null);

Update the handler to toggle/store an index.

const handleDropdown = (index) =>{
  setDropDown(value => value === index ? null : index);
}

In the rendering section, simply check if the current index matches the dropdown state.

<div
  onMouseEnter={() => handleDropdown(index)}
  onMouseLeave={() => handleDropdown(index)} // <-- handle index in mouse leave
  className={`chat__message ${
    item.name === user.displayName && "chat__reciever"
  }`}
>
  <h5 className={"chat__messageUser"}>{item.name}</h5>
  <p className={"chat__messagetext"}>{item.message}</p>
  {dropdown === index && ( // <-- check index match with dropdown value
    <Button>
      <ArrowDropDownIcon />
    </Button>
  )}
  {item.img && (
    <img alt={""} className={"chat__img"} src={item.imgURL} />
  )}
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Sudoku game board using underscore templates

Currently, I am in the process of constructing a Sudoku board using underscores templating. However, I have hit a roadblock when it comes to tackling the mathematical aspects necessary for deriving the table structure. My approach involves utilizing a 1d ...

Tips for customizing the scrollbar in React Virtuoso

To maintain a consistent style across different devices, I am planning to incorporate the use of "react-simple-scrollbar". It seems to work well with a traditional overflow div but encounters issues with Virtuoso. How can I address this problem? Below is ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

Ways to showcase information in a grid column

When looping through a dataset, I am encountering an issue where the display output is in rows instead of columns. <Grid direction="column" container> <Grid xs={6} item> {name} </Grid> </Grid> The current result lo ...

Which element from the context menu has been selected?

We specialize in creating browser extensions for Chrome, Firefox, and Safari. Our latest project involves implementing context menus within the extensions that will appear when users right-click on any editable form element. I attempted to incorporate an e ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Sending a PDF generated with jsPDF to an API without the need for downloading it from the front end

I have been successful in generating a PDF on the front end and downloading it using the code below. However, I am now faced with the challenge of sending this generated PDF to the server via an API call using fetch or Axios. Despite my research efforts, ...

Creating a server that is exclusive to the application in Node.js/npm or altering the response body of outgoing requests

As I work on developing a node app, the need for a server that can be used internally by the app has become apparent. In my attempts to create a server without listening to a port, I have hit a roadblock where further actions seem impossible: let http = ...

Creating a tool that produces numerous dynamic identifiers following a specific format

I am working on a function to create multiple dynamic IDs with a specific pattern. How can I achieve this? followup: Vue.js: How to generate multiple dynamic IDs with a defined pattern Details: I am developing an interactive school test application. Whe ...

Maintain dropdown menu visibility while navigating

I'm having an issue with my dropdown menu. It keeps sliding up when I try to navigate under the sub menu. I've spent all day trying to fix it, testing out various examples from the internet but so far, no luck. Any help would be greatly apprecia ...

What is the best way to activate a CSS animation?

I've hit a roadblock while attempting to trigger a CSS animation. Here's my CSS: h3[id="balance-desktop"]{ color: black; -webkit-animation-name: gogreen; -webkit-animation-duration: 2s; animation-name: gogreen; animation-du ...

What methods can I utilize to increase the speed of my JavaScript animation?

Recently, I implemented a Vue component designed to loop a div over the X axis. While it functions correctly, I can't help but notice that it is consuming an excessive amount of CPU. I am interested in optimizing this animation for better performance. ...

What is the proper way to utilize the value of a Node.js promise in a different function?

In my Node.js application, I have two functions defined. The first function is structured like this: function checkAdd ( address /* : string | void */ ) /* :Promise<Object[]> */ { var convertToLowerCase = address.toLowerCase() return Promi ...

Switch up the text when the image link is being hovered over

Is there a way to change the text color of the "a" tag when it is not wrapping the img link? <li> <a href="# WHEN I HOVER THIS IMG LINK I WANT A TAG BELOW TO CHANGE COLOR"> <img alt="Franchise 16" src="#"></img> < ...

Experience seamless transitions with Material UI when toggling a single button click

When looking at the examples in the Material UI Transitions documentation, I noticed that there are cases where a button triggers a transition. In my scenario, I have a button that triggers a state change and I want the previous data to transition out befo ...

Tips for improving performance in React by utilizing callback functions to eliminate lag when using setState

How can I improve performance in setState by using a callback function in React? I attempted to use a callback but the state is still lagging and I am unable to map the data in the array state. improvePerformance(){ ServerAddr.get(`/dis ...

React Navigation - Error: Attempting to access the property 'toUpperCase' of an undefined value

Running into an issue while working with React. Unable to find a solution so far. The stack trace isn't very helpful due to webpack bundling. This is the output I see in the console: [HMR] Waiting for update signal from WDS... Warning: React.createE ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

next-pwa is failing to generate service worker files

I've been working on a project using react.js and next.js, and I recently decided to turn it into a PWA app by implementing next-pwa. Following the instructions provided in the pwa-next docs, when I try running npm run build, no workbox-*.js or sw.js ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...