Home > Back-end >  How to change style just one element that clicked in map React?
How to change style just one element that clicked in map React?

Time:12-14

I want to scale only one element in the map when clicking on the picture. I read that I have to use an index but I don't know how to do it. I also saw how to do it in inline "onclick" by passing index there. But I want to do it with separated function.

Here is the code :

import './App.css';
import { useSelector, useDispatch } from 'react-redux';



import { useEffect, useState } from 'react';
import { birds, mountains,trees, search } from './features/slices/photoSlice';



function App() {
  const url = useSelector((state)=>state.url)
  const dispatch = useDispatch()

  const [photos, setPhoto] = useState('')
  const [scale, setScale] = useState(false)
  const [photoindex, setPhotoindex] = useState(0)

  useEffect(()=>{
    fetch(url).then(res=>res.json()).then(data=>setPhoto(data))
  },[url])


const handleSearch = (e) =>{
 
 if(e.key==='Enter'){
  e.preventDefault()
  dispatch(search(e.target.value))
 }
  
}
const handleClickOnPicture = (e) => {
  if(e){
    setScale(!scale)
  }
}
  return (
    <div className="App">
// Problem is here below:
       {photos?photos.hits.map((photo, index)=>{
        return <img className={scale?'m-5 h-80 scale-125':'m-5 h-80'} onClick={handleClickOnPicture} key={photo.webformatURL} src={photo.webformatURL}/>
       }):""}
      
      </div>
      </div>
    </div>
  );
}

export default App;

I removed half of the code, so you will see only the problem.

CodePudding user response:

use event.target.classname to add/remove classes

const handleClickOnPicture = (e) => {
  if(!e.target.classList.contains('scale-125')){
    e.target.classList.add('scale-125') 
  }
  else{
    e.target.classList.remove('scale-125') 
  }
  

}

 <img className='m-5 h-80' onClick={handleClickOnPicture} key={photo.webformatURL} src={photo.webformatURL}/>
    
  • Related