What is the best way to show a CSS class on the user's side in our React app?

To showcase the styling I have used, how can I pass the CSS class where my styles are defined in a React component? The JavaScript file and CSS file are separate entities with styles written in the CSS file.

.SideBar{
    border: 1px solid black;
    height: 700px;
    background-color: silver;
    margin-top: 5px;
}

Now, I want this class to reflect on the user interface. What should I include in the JS portion? import classes from './Project.module.css';

The styling properties function correctly on the JSX element but I desire for the user to be able to view these properties. How can I achieve this in JSX?

Expected Output :- On UI

.SideBar{
    border: 1px solid black;
    height: 700px;
    background-color: silver;
    margin-top: 5px;
}

What steps should I take?

Answer №1

You have the option to include the style directly within a style tag in the component code, allowing you to showcase the styling to the user.

To see how this is done, refer to this guide on writing the style tag within the render function:

If you're interested in displaying the style tag itself, check out this resource: https://css-tricks.com/show-and-edit-style-element/.

Just like this example:

class App extends React.Component {
  render() {
    return (
    <div className="App">
      <h1>Show me your style!</h1>
      
      <style dangerouslySetInnerHTML={{__html: `
      body style { 
        display: block; 
      }
      h1 { 
        color: blue;
       }
    `}} />
    </div>
  );
  }
}

While it may not be the prettiest solution, it can be effective for your needs.

Best of luck with your styling endeavors!

Answer №2

When working with React, you will need to utilize the className attribute in your JavaScript file in order to apply CSS styles.

For example:

CSS file:

.menu {
background-color: coral;
}

JS File:

Begin by importing your CSS file into the JS file

render() {
  return <span className="menu">Menu</span>
}

By following this structure, you can effectively incorporate CSS styling within your JS file.

Answer №3

How about this?

console.clear();
{


  function getStyle(className) {
    "use strict";
    className = className.replace('.', '\.');
    var styles = Array.from(document.styleSheets).reduce((carry, sheet) => {
      var rules;
      try { // CORS
        rules = sheet.rules || sheet.cssRules;
      } catch (e) {
        return carry;
      }
      if (!rules) { return carry }
      
      rules = Array.from(rules).reduce((carry, rule) => {
      
        if (rule.selectorText && rule.selectorText.match(className)) {
          carry.push(rule.cssText || rule.style.cssText);
        }
        return carry;
      }, []);
      if (rules.length) {
        carry.push(rules)
      }
      return carry;
    }, [])
    return styles[0];
  }

  function getElementsWithClasses() {
    return Array.from(document.querySelectorAll('[class]'));
  }

  function over(el) {
    var display = document.getElementById('display-fsadhkfjdfkds');
    if (!display) {
      display = document.createElement('div')
      display.setAttribute('id', 'display-fsadhkfjdfkds');
      document.body.append(display);
    }
    display.innerHTML = "";
    var html = Array.from(el.classList).reduce((carry, cl) => {carry += getStyle(`.${cl}`); return carry}, "");
    display.innerHTML = html;
  }
  function out(el) {
    var display = document.getElementById('display-fsadhkfjdfkds');
      if (display) {
        display.remove()
      }
  }
                                     
  var elems = getElementsWithClasses()
  
  
  window.addEventListener('mouseover', e => {
    if(e.target.classList.length) {
      over(e.target)
    }
  })
  document.addEventListener('mouseout', e => {
    if(e.target.classList.length) {
      out(e.target)
    }
  })
}
.abra, .ca {
  background-color: lightgray;
}
.abra {
  color: pink;
}
.dabra {
  color: blue;
}
.not-used {
  padding: 200px;
}
.date {
  padding: 20px;  
}

[class]:hover {
  background-color: lightgray;
  box-shadow: 0px 0px 5px 1px #800000;
}

#display-fsadhkfjdfkds {
  position: fixed;
  bottom: 5px;
  right: 5px;
  width: calc(25vw - 2 * 5px);
  height: calc(50vh - 2 * 5px);
  border-radius: 10px;
  background-color: cornsilk;
  border: 1px solid darkgreen;
  box-sizing: border-box;
  padding: 10px;
}

html, body {
  min-height: 100vh;
  min-width: 100vw;
}
<code class="abra ca dabra" data-do-it="dont">No code</code>
<div class="extra">
  Extra
</div>
<span>No class</span>
<table>
  <tr>
    <td class="date"><time class="year" style="color: red">2020</time></td>
    <td>Event 1</td>
  </tr>
</table>

New

What do you think of incorporating CSS and the :after pseudo element with a class attribute as content?

*[class]:after {
  content: "." attr(class);
  color: gray;
  font-size: .75em;
  vertical-align: super;
}
<div class="dig"><span>No</span> <span class="spa">questions</span> <span>asked</span></div>

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

Setting a radio button to be checked in AngularJS using stored data

I am facing an issue with the radio button for the account type. Even though it is correctly stored in the database, it does not display when I first load the page. However, upon clicking any of the radio buttons, it updates the value and shows as checked. ...

Using Vue to display a Div inside a TD element of a table does not result in a reactive behavior

I am encountering an issue with a table where the last column contains a div with three options (View, Edit, and Delete). This submenu is initially hidden, but when clicking on the options button in the last column of the table, the array used to control i ...

Modify the input class once an image has been chosen (But not yet submitted)

Looking for a solution to update background image when file is selected <input type="file" class="imgupload" name="file" /> I've created image uploader with a hidden form element inside a padded div, displaying a background image. Want to chan ...

When data is submitted through the POST method, it mysteriously disappears

When I send the "user" variable to another page called Survey.php, here's how it looks: In the index.html file: <form action="Survey.php" method="post" name="frm"> <div><input type="text" name= ...

Can onerror be triggered on an HTML Image onload event?

Having an html image labeled as follows: <image src = 'image.png' onerror = "handleError(this)" onload = "handleLoad(this)"> function handleError(n){ getFirstChild(n.parentNode).style.display = '',n.style.display ...

What is the best way to duplicate a text using a button in ReactJS?

Hey there, I'm working with an array and trying to figure out how to copy the text in a p element ({item.adress} => this is part of an array item) when a button is clicked. Could you lend me a hand? import classes from './CryptoBox.module.css& ...

Ninja Flip ComboButton

I am looking to enhance the functionality of a toggle button within a web application that was developed using the JS Dojo API. Currently, the button is utilizing dijit.form.ToggleButton, but I need it to include an additional feature for a dropdown menu w ...

Strategies for avoiding JavaScript and Flash navigateToURL attacks

On one of my online platforms, I have integrated third-party flash files. However, I am looking for ways to prevent these flash files from executing any redirects on my website. ...

It appears that my React component is not being rerendered even after using componentDidMount and setState to update it

/*I have successfully fetched data and set it to state, however, when attempting to generate an array of jsx items for display, the array appears empty and nothing is rendering. I tried hardcoding and it worked. I also logged the data which showed that th ...

Attempting to pass an asynchronous initial state to the useReducer method is resulting in an undefined return value

I am facing an issue where I am fetching asynchronous data in the parent component and trying to use it as initialState in VersionContainer. However, when I pass this initialState to the context provider, the values in ContentVersionProvider end up being ...

Unlock AngularJS expression through ng-click functionality

I've encountered an issue with accessing AngularJS expressions after a click event takes place. index.html <div class="row"> <a href="#/company"><div class="tile col col-comp cat-a-g grow-appear" ng-click="onSelect(item)" ng-repea ...

Styling CSS for circular buttons

I am a newcomer and feeling quite puzzled. When using a div tag with the same width and height along with border-radius: 50%, it always transforms into a circle. However, when attempting to create a circular button using the 'a' tag, it doesn&apo ...

The functionality of saving a file using the jsPDF method is not functioning properly

After dedicating four days to resolving a seemingly straightforward task that involved the jsPDF library, I found myself faced with a challenge. My goal was to save a file using this library, not just print it like I had successfully done before. This is ...

Enabling communication between App.js and a separate class in React

How can I integrate React Scheduler with JSON data in my app and pass shifts and functions from App.js to DataSheet.js for updating the data? Is there a more efficient way to enable database updates directly from DataSheet? App.js: import React from &apos ...

Leveraging the power of $lookup and $mergeObjects in aggregation

I'm looking to join a collection. Previously, I used only lookup to get separated fields that are joined, but now I need the results similar to MySQL join. I have tried using $lookup and $mergeObjects for this action, but they are not working well. H ...

JQuery Form Wizard - Adding a Finish Button Linked to a Page

Having some difficulty linking the finish button on my Jquery Form Wizard within my Flask App to a link. I attempted to test the functionality by creating a simple alert, but that didn't work either. I'm certain that I missed a step somewhere, b ...

Utilize jQuery to toggle the visibility of a div depending on the numerical quantity input

I would greatly appreciate any assistance with this request, please. Here is the input that I have: <input onchange="UpdateItemQuantity(this.value,1284349,0,10352185,2579246,'','AU'); return false;" type="number" class="form-contro ...

Guide to creating a navigation bar that expands when you expand navigation items

My portfolio website features a handful of navigation items for various views. I simply copied the default navigation code from the Bootstrap site. However, when I expand the "hamburger" menu, the navigation remains the same size, causing the expanded item ...

Tips for troubleshooting the error message "is not a function" in a React application

Hi there, I'm currently delving into learning React and have encountered an issue that says: (TypeError: newsData.map is not a function) in my browser when running my code. Oddly enough, Visual Studio Code doesn't flag any errors, only Chrome doe ...

Retrieving column values from a Datatable is limited to the first 10 rows

Trying to extract the values from column 1. I followed the instructions provided in the datatable documentation: var data = table.column( 0 ).data(); Table setup: var datatable = table.dataTable({ "scrollX" : "100%", "scrollY" ...