Is it considered a best practice in React to modify styles of elements using the className state?

I have a unique component that can showcase either an error message or a success message. These are the only two possible "states" it can be in, so the styling is limited to either of these options: for success:

background-color: green;

for error:

background-color: red;

Would it be considered a best practice to have a state for the component that changes the "className" property to either info__success or info__error, with the corresponding styling defined in a CSS file like this:


.jsx

const errorClassName = "info__error";
const successClassName = "info__success";

const [ classState, setClassState ] = useState(errorClassName);

return (
  <div className={classState}>Message</div>
)

.css

.info__error {
  background-color: red;
}

.info__success {
  background-color: green;
}

I am aware that I could use a simple list as a state like below, but it can get messy especially when there are multiple CSS styles to update.

 
const [ error, setError ] = useState(true);

const style = {
  background-color: error ? "red" : "green",
}

return (
  <div style={style}>Message</div>
)

Is there a cleaner and more practical way to achieve this without cluttering the code? I am not a fan of adding CSS directly into my JSX files, and I am not a big fan of tailwind either.

Answer №1

The second option you've presented is indeed a step in the right direction compared to the first. However, there is a third approach that aligns better with common production code practices and may be more suitable for your needs. I suggest utilizing state to monitor the presence of errors, similar to your second example. Then, leverage the error state to determine the appropriate class, similar to your first example.

const [hasError, setHasError] = useState(false);

return (
  <div className={hasError ? 'info__error' : 'info__success'}>Message</div>
)

In my view, directly modifying styles is acceptable if you're not using a utility framework such as TailwindCSS. It may not be problematic initially, but could become cumbersome as styles become more complex (with multiple properties). I would advise against storing the class string directly in state.

The class name is essentially a byproduct of what you're truly monitoring: the error state. By managing the error state directly, you can easily incorporate additional functionalities, particularly for accessibility purposes (a color change is irrelevant to someone who is visually impaired). This could involve displaying a hidden error message by default and/or handling focus management.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrow indicating the correct direction to expand or collapse all items with a single click

I have successfully implemented the "expand/collapse all" function, but I am facing an issue with the arrow direction. The arrows are not pointing in the correct direction as desired. Since I am unsure how to fix this problem, I have left it empty in my co ...

Extract JSON data from a web address using JavaScript

A unique system has been created to parse JSON and style it using CSS. Instead of outputting the data within the script, the goal is to retrieve data from a local or remote URL. <script type='text/javascript'> $(window).load(function(){ va ...

Step by step guide on customizing material-ui component styling

I need assistance in adjusting the width of SnackbarContent by overriding the root css API. How can I achieve this? <SnackbarContent className={classNames(classes[variant], classes.badge)} classes={{ root: { maxWidth: &apo ...

"Mastering the art of traversing through request.body and making necessary updates on an object

As I was reviewing a MERN tutorial, specifically focusing on the "update" route, I came across some interesting code snippets. todoRoutes.route('/update/:id').post(function(req, res) { Todo.findById(req.params.id, function(err, todo) { ...

What are some ways to utilize an empty array that has been declared in React's initial state?

I am currently in the process of developing an application that displays a collection of various lists. However, I have encountered a roadblock when attempting to access an empty array that I initialized when setting up the initial state. Here is the state ...

The $scope in Angular doesn't seem to be working as expected in the callback function, despite using $scope

I'm currently working on converting the JSFiddle found here to AngularJS: http://jsfiddle.net/danlec/nNesx/ Here is my attempt in JSFiddle: http://jsfiddle.net/leighboone/U3pVM/11279/ var onAuthorize = function () { updateLoggedIn(); $scope. ...

Issue with AngularJs: $http post only posting single item to collection inside a for loop

I have a collection that requires me to post multiple items in a for loop. Below is the code snippet: for(i = 0; i < 28; i++) { var request = $http({ method: "post", url: "/students", ...

Use React to increment a variable by a random value until it reaches a specific threshold

I am currently working on creating a simulated loading bar, similar to the one seen on YouTube videos. My goal is for it to last 1.5 seconds, which is the average time it takes for my page to load. However, I have encountered an issue with the following co ...

Is the WordPress error message "wp_register_style was improperly called" showing up on

I am facing an issue while trying to incorporate this code into my initial Wordpress template. It seems that the libraries for Bootstrap and my custom styles are not functioning as expected. Here is the code snippet in question. Any insights would be great ...

Mongoose discovers an unexpected empty array

My task is to locate a SoldProduct with an intimeOrderNumber value of '3'. var query = { intimeOrderNumber: '3' }; However, my search result returns an empty array. SoldProduct.find(query, function(err, soldProducts) { if (err) { ...

Removing a cookie in Javascript - step by step guide

Cookie Conundrum: I've encountered a curious scenario involving browser cookies. After entering an invalid login ID, an unauthorized cookie appears on my HTML page. Despite my attempts to display and expire the cookie, it stubbornly remains persistent ...

Automatically toggle Bootstrap checkbox switch to OFF upon successful completion of AJAX script

On my Employee screen, I have an HTML Form with a Bootstrap Checkbox Switch that toggles the visibility of password change fields. Clicking it reveals or hides the fields accordingly. I'd like to set this switch to "off" when the AJAX script updates ...

In Safari, Angular 6 fails to display data points when a component is routed to the d3/event-drops

After creating a test app to replicate the current issue, I have come across an interesting problem. Here is the link to the codebase: https://github.com/mohammadfarooqi/event-drops-d3-test-app. You can also view a sample demo deployed (recommended in saf ...

What is the process for rendering a new component in React by utilizing the onTitleClick property of Material-UI AppBar?

Looking for a way to incorporate a new component by utilizing the onTiTleClick property. Below is the code snippet for my component: import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from ...

Issue with the formatting of the disabled button

I am facing an issue with styling a disabled button. Whenever I try to apply custom styling, it reverts back to the default styling. I have already cleared my cache but the problem persists. The button is disabled using JavaScript with document.getElementB ...

Implementing Title Attribute in Grid View Template Field

I have implemented a Grid View with a "TemplateField" that includes properties for Header Text and SortExpression set to true. Upon inspecting the browser, I noticed that it generates an anchor element with some JavaScript. How can I add a title tag to t ...

What is the method for combining two box geometries together?

I am looking to connect two Box Geometries together (shown in the image below) so that they can be dragged and rotated as one object. The code provided is for a drag-rotatable boxgeometry (var geometry1). What additional code do I need to include to join t ...

Try utilizing the array find() method in place of a traditional for loop

Is there a better way to refactor this code using the Array.find() method instead of nested for loops? onLoadTickets() { const ticketsReq = this.ticketService.getTickets(); const tariffsReq = this.tariffService.getTariffs(); forkJoin([ticketsR ...

When the web driver fails to function as expected

After installing the selenium-webdriver via npm, I downloaded the IE component from this link and added it to my path on Windows 8. Upon opening IE, I had to set all security zones to high, ensuring they were consistent. However, due to restrictions in th ...

Upon attempting to open Google Maps for the second time, an error message pops up indicating that the Google Maps JavaScript API has been included multiple times on this page

Currently, I am utilizing the npm package known as google-maps and integrating it with an angular material modal to display a map. However, upon opening the map for the second time, an error message is triggered: You have included the Google Maps JavaScri ...