How can I apply conditional styles in React using Sass?

My SCSS file includes the following classes:

.errorNotice {
  display: none;
  font-size: 12px;
  color: #D85B5F;
  background: white;
  padding: 5px;

  .error & {
    display: inline-block;
  }
}

Within my render function,

{this.state && this.state.error ?
     (
     <p className={styles.errorNotice + (this.state.error ? styles.error : '')}>{this.state.error}</p>
     ) :
     null
}

However, the output does not meet my styling requirements. It is displaying a strange concatenation:

campaigns-components-WaitlistForm-styles_errorNotice-1X-Ty4campaigns-components-WaitlistForm-styles_error-JNXx2E

I aim to correctly display the errorNotice with the appropriate display attribute.

Thank you

Answer №1

To concatenate strings, utilize string literals. When dealing with class names, simply specify the class name without any additional markup. By utilizing the backtick symbol ` , you can initiate a string literal and embed JavaScript code within ${} to process and output data:

   <p className={`errorNotice ${this.state.error ? "error" : ''}`}>{this.state.error}</p>

If you're looking for an alternative approach, consider exploring styled-components (). Personally, I find this solution quite convenient for React projects as it eliminates the need for separate CSS files or manual management of class names.

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

The appearance of unnecessary empty spaces at the conclusion of the page

.article-image1 { height: 256px; width: 256px; } .article-image1:before { content: ''; position: absolute; height: 100%; width: 100%; top: 0; left: 0; background-image: url(http://limootoys.com/wp-content/uploads/gentleman-e150 ...

MVC error encountered when attempting to pass the parameter '&' results in failure

Encountered an error in MVC while passing '&' as a parameter, which fails to display the desired outcome. How can I address this issue with the following example? public IActionResult Create(int? idTrabalhador, [FromQuery]string GridState{} ...

Learn the process of pulling information from mongoose and incorporating it into all pages

I am currently developing a basic website where users need to register and subscribe to activated challenges. I am utilizing passport for user registration, login forms, and saving user email and password in the database. However, I am facing an issue when ...

Ways to access the entire parent element, rather than just the individual child element, following the use of e.target

Looking to target the li element itself when clicked, rather than its child elements. The goal is to determine which specific option the user selects from a dropdown menu using event.target in jQuery. If the user chooses an li with a class of 1, set one gl ...

What is the best way to change an http call in a controller to a Service/factory pattern that accepts a parameter?

Currently, I have a controller making use of http.get, http.push and http.post methods within my AngularJS app. During my learning journey with AngularJS, I've discovered that it's more efficient to place http.get calls in service files. While I ...

Seamless creation of numerous SystemJS/JSPM modules

Currently, I am tackling a series of JavaScript projects that have interdependencies between them. My choice of using JSPM as the package manager has been going smoothly so far. However, for efficient and seamless development, I am seeking the best approac ...

Ensure page is updated after an AJAX request in jQuery Mobile by refreshing the page

My jQueryMobile page structure in index.html looks like this: <div data-role="page"> <div data-role="header">...</div> <div data-role="content">...</div> <div data-role="footer">...</div> </div& ...

Exploring Symfony2: Enhancing user experience with dynamic form submission and dropdown menu updates

Starting from the beginning. I have a tab-panned layout with links. Upon clicking a link, a drop-down checkbox form is injected directly into the HTML through $(".dropdown-toggle").click(function() { var projectId = $("#permission-form").attr("data-p ...

Spin Sphere on x-Axis Using Mouse Location in three.js

I have a sphere with an earth texture on it using three.js. The earth rotates horizontally on its own y-axis, but I'm looking to rotate the sphere vertically on its x-axis based on mouse position. When the mouse is at the top of the browser window, th ...

Getting information from MySQL database with just HTML and JavaScript

Looking to securely access a MySQL database on my localhost using only HTML and JavaScript. No need for server-side scripting or web servers. Any tips on how to make this happen? ...

Steps for deactivating tab stops on the primary webpage in the presence of a snackbar

On my web page, there are multiple drop-down menus, input fields, and buttons that can be interacted with using both the tab key and mouse. After entering certain data, I trigger a snackbar (source: https://www.w3schools.com/howto/howto_js_snackbar.asp) t ...

Extending a Sub-Object in JavaScript

I'm attempting to include new attributes to the sub-object within object1. However, I am facing issues with it being overwritten. const object1 = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } }; const object2 = Object.assign({ j: 4, ...

Margin discrepancies when using em units

Currently, I am utilizing an em-based margin for items within a menu that are homogeneous in terms of markup, class, and id. It appears that the margins for each of these items should be rendered the same. However, some are displaying as 1px while others a ...

Ways to retrieve the highest date value in an array

I'm running into an issue where I am trying to find the maximum day in an array of dates, but for some reason it keeps returning either Invalid Date or null. I'm not sure what's going wrong. Do you think I should convert the values to a diff ...

Using ng-if in AngularJS to compare two objects

I am transferring between controllers with different formations, and I am attempting to use "ng if" to compare the ids, but it is not functioning as expected. Below is the code snippet: var postsApi = 'http://mywebsite.com/wp-json/posts?filter[p ...

Switching the color of links when they are focused, without changing it when they are clicked by either a mouse or

Is there a way to change the color of a link only when a user navigates to it using the TAB key and not when they click on it? The simple CSS solution I found was: a:focus { color: red; } However, this also changes the color when the link is activated by ...

Steps for positioning a div beside a centered div

Is there a way to position a div next to another div that is centered on the page, like this: .firstDiv { margin-left: auto; margin-right: auto; padding: 0; } The above code centers the first div in the middle of the page. But how can I add a ...

Switching from module.exports in Javascript to Typescript format

My Node-express code currently uses module.exports to export functions. As I am converting the code to TypeScript, I need to find out how to replace module.exports in typescript. Can you help me with this? ...

The Form is causing an error with the Ant Design Switch because of the value

I am creating Ant Design Form.Item dynamically in Next JS and it looks like this: <Form.Item initialValue={initValue} key={property.key} name={property.key} label={property.name}> {component} </Form.Item> When the component is a Switch, it ...

sending a POST request with fetch

When it comes to making AJAX requests, I used to rely on jQuery in the past. However, with the rise of React, there is no longer a need to include the entire jQuery library for this purpose. Instead, it is recommended to use JavaScript's built-in fetc ...