Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Change the image src of a div element in a grid on a keypress event in React

I am building a navigable grid with arrow keys. Everything works fine, but I would like the focused element to change the img when selected from an img to a gif.

I tried to give it the same name that I used to import the image, like the element id tag. But this didn't work. React interprets the id tag as a string and not the path name to that image.

Any ideas how to get React to interpret the element ID as the image path to look up?

import items from './assets/images/items.png'
import items2 from './assets/images/items.gif' 
 useEffect(() => {
                let i = 0 
                const handleKeyPressed = (e) => {
                        //to focus the right element
                        if (['KeyD', 'ArrowRight'].includes(e.code) ) {
                                i = ++i
                                let menuElement= document.getElementsByClassName('menu-image')[i]
                                menuElement.style.border="solid 3px"
                                const dynamicString = document.getElementsByClassName('menu-image')[i].id
                                menuElement.src=dynamicString//React interprets it as a string
 
                                
                        }
                }
                window.addEventListener('keydown', handleKeyPressed);
                return () => {
                window.removeEventListener('keydown', handleKeyPressed);
                };
}, []);
<div className='menu-grid'>
                <div className="menu-item">
                    
                <img id="items" className="menu-image" alt="a draw of a bag" src={items2} style={{ border: 'solid 3px'}}
                        onPointerOver={e => {
                                e.currentTarget.src = items2
                                e.target.style.border="solid 3px"} 
                        } 
                        onPointerLeave={e => {
                                e.currentTarget.src = items
                                e.target.style.border="solid transparent 3px"}
                        }/>
                        <span> Items </span>
                    
                </div>
</div>
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!