React change class of component without using state

Viewed 340

How can I change the className or style of a div without using state or any third party libraries? Lets say I click on a button, and I need to change the background color of a div how can I do that?

<Affix onChange={() => change css or class} offsetTop={60}>
<div>...</div> // Change css of this div
</Affix>
2 Answers

You can either do it manually using state:

const [myClass, setMyClass] = useState('bgColor-white');

return (
  <Affix onChange={() => setMyClass('bgColor-black')} offsetTop={60}>
    <div className={myClass}>...</div> // Change css of this div
  </Affix>
)

Or you can use a library that handles dynamic styling. I use and recommend styled-components

You can change any attribute or property of a Component (Element) in React by using basic javascript functions.

onClick={(e) => {
    e.currentTarget.setAttribute("src", newUrl);
}

Will change an image the moment you click on it, without using Ref or State. event.currentTarget will give you the reference to the component that fired that particular React.MouseEventHandler event, and with the Element's reference, you can manipulate it at will.

This is particularly useful when you need to change an attribute in a component in a map loop without needing to keep track of it.

Edit: A friend of mine just gave me a better one for classes in specific:

e.currentTarget.classList.add('my_custom_klass')
Related