Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React change class of component without using state

Tags:

reactjs

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>
like image 630
hernandeΩ Avatar asked Sep 08 '26 22:09

hernandeΩ


1 Answers

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')
like image 85
Matt DF Avatar answered Sep 11 '26 18:09

Matt DF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!