Search code examples
reactjsuse-ref

reactJs useRef to add or Remove className


How to Add className or Remove ClassName using useRef

code follows

const refs = useRef("");
 const clicka =()=>{  ref.current.classList.add('correct')  }

<div onClick={()=>{clicka()}} refs={ref} className="js-choose-answer"><div>a</div>{user.opt1}</div></div>

i can Access className Value ref.current.className but unable to add

code

import React, { useState, useEffect,useRef} from 'react';


const Slugg = ({user}) => {
//onClick to set className "js-choose-answer correct"

return (
    <div>
 <div className="__options">
                           
  <div onClick={()=>{clicka(user._id)}} ref={ref}  className="js-choose-answer"><div>a</div><{user.opt1} </div></div>
   </div>

 <div className="__options">
                           
  <div onClick={()=>{clicka(user._id)}} ref={ref}  className="js-choose-answer"><div>a</div><{user.opt1} </div></div>
   </div>
</div>
)

}

Solution

  • Try this using useState. Set a boolean corresponding to user id which rerenders the elements with classname correct

    const [status, setStatus] = useState({});
    
    const clicka =(userId)=>{  
         setStatus(prevStatus=>{
             return {...prevStatus, [userId]: true}   
          }) 
     }
    
    <div onClick={()=>{clicka(user._id)}} className={`js-choose-answer ${status[user._id] ? 'correct': ''}`}>< 
          <div>a</div><{user.opt1} </div></div>
    </div>