Home > front end >  Update className using react hook
Update className using react hook

Time:02-27

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

CodePudding user response:

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.

CodePudding user response:

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


  • Related