How to add a CSS class to an element with React function components

Viewed 5948

i would like to know how can i add a CSS class to an element which has no any CSS classes.I am looking React Functional component solution with Hooks. Here i want to add class to tag and i don't need to add ${myclass} in advance. That means tag should be without any attributes before we execute the addclass functionality. I tried the following method and needs to get a best practice on it. Thanks in advance!

function Trial(){
  const [myclass, changeclass] = useState("");
  const addclass=()=>{
  changeclass(`active`)
  }  
  return(
    <div>
      <h1 className={` ${myclass}`}>Hi</h1>
      <button onClick={addclass}>Click it</button>
    </div>
  )
}
2 Answers

You can add an id and then manipulate the element in the DOM by queryselector

in the element you want to change its className

 <h1 className={`${myclass}`} id = "change-class">Hi</h1>

and then in the function

  const addclass=()=>{
      document.querySelector("#change-class").classList.add('new-class-name');
  } 

so the whole code would look like this

function Trial(){
 const addclass=()=>{
      document.querySelector("#change-class").classList.add('new-class-name');
  }  

return(
    <div>
     <h1 className={`${myclass}`} id = "change-class" >Hi</h1>
      <button onClick={addclass}>Click it</button>
    </div>
  )
}

For more info check here and here

You can use useRef() hook for this:

function Trial(){
  const ref = useRef(null);
  const addclass=()=>{
     const h1 = ref.current; // corresponding DOM node
     h1.className = "active";
  }  
  return(
    <div>
      <h1 ref={ref} className="">Hi</h1>
      <button onClick={addclass}>Click it</button>
    </div>
  )
}
Related