Home > front end >  reactJs useRef to add or Remove className
reactJs useRef to add or Remove className

Time:09-06

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>
)

}

CodePudding user response:

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>

CodePudding user response:

I usually do this and it works

const currentElement = useRef(null)

const switchClassHandler = () => {
    currentElement.current.classList.add('correct')
    currentElement.current.classList.remove('error')
}

return (
    <React.Fragment>
        <div ref={currentElement} onClick={switchClassHandler} className={'global error'}>
            hello
        </div>
    </React.Fragment>
)
  • Related