Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
Update className using react hook

I have a span which has a className . The span has two state, one is like

<span  key={uuid()} ref = {colorRef} className = 'singleWord'>{word}</span>

and the other is like

<span  key={uuid()} ref = {colorRef} className = 'singleWord redword'>{word}</span>

Now what I want is to check the className value like className.classList.contain("oneClass') which we do in vanilla js but I need in react hook(may be with ref hook) and also add className and remove className . also is it possible to check the length of className .for example 'singleword redword' should give length 2. So overall I need -

  1. add or remove classes
  2. check length
  3. check if class contains or not I need to check them in react hook could anybody suggest how to do ?? Thanks in advance
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can store in state an array of classes and use that to get all the information you need plus it gives an easy way to toggle any class in a set of classes.

basically this handleClasses function takes a class argument and then checks whether that class is already in your state. If it is, it removes it, if it's not, it add it to the state. Then in your span you join all the classes in the array in state to make a single string of classes.

Also you get the number of classes applied to your element very easily by doing classes.length

import React, { useState } from 'react';

const Component = () => {
  const [classes, setClasses] = useState(['singleWord']);

  const numberOfClasses = classes.length;

  const handleClasses = (c) => {
    setClasses(classes.includes(c)
      ? classes.filter((cls) => cls !== c)
      : [...classes, c]
    )
  }

  return (
    <span
      onClick={() => handleClasses(passClassToToggleHere)}
      className={classes.join(' ')}
    >
      text
    </span>
  )
};


about 4 years ago · Juan Pablo Isaza Report

0

If you are using colorRef = useRef() hook, then you can obtain the target node by calling colorRef.current and proceed with vanilla js methods like colorRef.current.classList.contain("oneClass') and so on.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!