1

How can we dynamically change the properties of a CSS Class in ReactJS. For example, I have several text fields with CSS Classname "important". I want to change all of them to have flash a red background on click of a button.

I thought I could do this by changing the properties of that CSS Class. How do I alter this class so that all its the text fields with that class will change in a flash.

Or is there another more elegant way of doing this?

3
  • Generally a better approach is to add/remove modifier classes, rather than changing the CSS dynamically. (And avoiding !important where ever possible is also a good goal) Commented May 17, 2022 at 9:59
  • @DBS Thanks, But how do I modify all those text fields at a time? Is there a way to query / select several elements for update? Commented May 17, 2022 at 10:00
  • If you add the code for the relevant component to the question we might be able to answer in more detail. But passing in an extra class to multiple input components shouldn't be too difficult, e.g. using a template string Commented May 17, 2022 at 10:03

2 Answers 2

1

In your render() method, use a state variable to attach different classes to the rendered element depending on its state.

Sign up to request clarification or add additional context in comments.

2 Comments

O! Why didn't I think of that! Thanks.
No probs. In case you've missed this nice tutorial: reactjs.org/docs/thinking-in-react.html ;)
0

You can do something like conditionally passing classes in your className={""} prop.

If state changes class name will be changed also.

It will look something like this:

className={state ? "important" : "yourDesiredClass"}

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.