5

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
  • Looking good! I would rename the addClass function since it's not adding class it's more replaceClass or editClass since it's overwrite the class Commented Jul 13, 2021 at 7:53
  • @GiladTamam, actually i already added a class because react need a default state there. Actually i don't need a class preadded in it. I need a blank element like this <h1> and the class needs added only after the function invokes. I hope this make sense. Commented Jul 13, 2021 at 8:06

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

7 Comments

it works and your idea is good. But let me know is it a best practice to do functionalities without React Hooks. Let me know.
Hooks are like ordinary functions and there is no difference between hooks and functions, and querySelector is a function as well, therefor it doesn't matter wether you use hooks or not.
Actually, there is no need to add an ID. It will work in the following method also. function Trial(){ const addclass=()=>{ document.querySelector("h1").classList.add('new-class-name'); } return( <div> <h1>Hi</h1> <button onClick={addclass}>Click it</button> </div> ) }
@RenJitsm Yes, but what if we add another h1 and then we decide to add class to the new one? We still can do it but it makes the code messy and it works fine for beginner who don't want to make big project there is no need for that when we can add id so i belive best practice is ids
Also if my answer was helpful, please mark it as accepted and vote it up so that future visitors will use it
|
4

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

3 Comments

Thanks for your attempt of help. But i got other solution based on ordinary functon inside component
You're welcome. Both solutions would work and it is entirely subjective which one you prefer. But for me, this solution is more inclined towards react way of doing things.
@RenJitsm, when you ask a question and then solve it, it's helpful to share the specifics of the solution you used so others who get your question in search results can get the answer as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.