3

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>
14
  • 1
    why not using state? Commented Dec 23, 2020 at 16:15
  • 1
    the proper way to do that in react is using state Commented Dec 23, 2020 at 16:17
  • 1
    if you don't want to use state then why use react you can do that with javascript main point is react work good with state and it handle it well so why not use state Commented Dec 23, 2020 at 16:20
  • 1
    @Chandan the reason is because I am dealing with a large amount of data on the page and if the user keeps activating and deactivating the navbar the page will re render hundreds of times Commented Dec 23, 2020 at 16:25
  • 1
    you can move navbar to another component with it state than you can change state and will not effect other components is it not possible to move navbar to another component Commented Dec 23, 2020 at 16:30

2 Answers 2

2

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')
Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

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.