Stop the infiltration of emotions into your style

Utilizing the JsonForms React Component to dynamically generate an HTML form in my web application. The framework I am using handles all view rendering on the server side. To integrate this component, I compiled a small react component by running npm run build which generated a main.js. I then included it in my app as follows:

<html>
  <head>
    ...
    <script type="text/javascript" src="main.js"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Although everything functions correctly, I noticed that the CSS styling of other elements on the page (outside of the component) has been altered when viewing pages containing the React component. Upon inspecting the computed styles in Chrome, I discovered that there is a <style> tag overriding the font-family applied to the body:

It appears that after page load, the <head> section includes style tags referencing the "emotion" library which are not present in the original server-sent page source:

I suspect that the javascript for my React component injected additional CSS styles into my page. Removing the <style> tag reverts the changes, such as the altered font-family.

How can I pinpoint where the .css modifications made by emotion are specified? Is there a method to configure or namespace a component styled with emotion to prevent unintended styling impacts on other page elements?

In essence, the JsonForms component I am integrating into my page mirrors the "seed" app provided by the JsonForms library:

import { Fragment, useState, useMemo } from 'react';
import { JsonForms } from '@jsonforms/react';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import logo from './logo.svg';
import './App.css';
import schema from './schema.json';
import uischema from './uischema.json';
import {
  materialCells,
  materialRenderers,
} from '@jsonforms/material-renderers';
import RatingControl from './RatingControl';
import ratingControlTester from './ratingControlTester';
import { makeStyles } from '@mui/styles';

const useStyles = makeStyles({
  container: {
    padding: '1em',
    width: '100%',
  },
  title: {
    textAlign: 'center',
    padding: '0.25em',
  },
  dataContent: {
    display: 'flex',
    justifyContent: 'center',
    borderRadius: '0.25em',
    backgroundColor: '#cecece',
    marginBottom: '1rem',
  },
  resetButton: {
    margin: 'auto !important',
    display: 'block !important',
  },
  demoform: {
    margin: 'auto',
    padding: '1rem',
  },
});

const initialData = {
  name: 'Send email to Adrian',
  description: 'Confirm if you have passed the subject\nHereby ...',
  done: true,
  recurrence: 'Daily',
  rating: 3,
};

const renderers = [
  ...materialRenderers,
  //register custom renderers
  { tester: ratingControlTester, renderer: RatingControl },
];

const App = () => {
  const classes = useStyles();
  const [data, setData] = useState<any>(initialData);
  const stringifiedData = useMemo(() => JSON.stringify(data, null, 2), [data]);

  const clearData = () => {
    setData({});
  };

  return (
    <Fragment>
      <div className='App'>
        <header className='App-header'>
          <img src={logo} className='App-logo' alt='logo' />
          <h1 className='App-title'>Welcome to JSON Forms with React</h1>
          <p className='App-intro'>More Forms. Less Code.</p>
        </header>
      </div>

      <Grid
        container
        justifyContent={'center'}
        spacing={1}
        className={classes.container}
      >
        <Grid item sm={6}>
          <Typography variant={'h4'} className={classes.title}>
            Bound data
          </Typography>
          <div className={classes.dataContent}>
            <pre id='boundData'>{stringifiedData}</pre>
          </div>
          <Button
            className={classes.resetButton}
            onClick={clearData}
            color='primary'
            variant='contained'
          >
            Clear data
          </Button>
        </Grid>
        <Grid item sm={6}>
          <Typography variant={'h4'} className={classes.title}>
            Rendered form
          </Typography>
          <div className={classes.demoform}>
            <JsonForms
              schema={schema}
              uischema={uischema}
              data={data}
              renderers={renderers}
              cells={materialCells}
              onChange={({ errors, data }) => setData(data)}
            />
          </div>
        </Grid>
      </Grid>
    </Fragment>
  );
};

export default App;

Answer №1

During my investigation into the seed application, I dissected various parts to identify the source of unwanted styling caused by a piece of code. Through this process, I discovered that the culprit was the <CssBaseline /> component (from '@mui/material') in the src/index.tsx file:

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <App />
  </ThemeProvider>,
  document.getElementById('root')
);

https://github.com/eclipsesource/jsonforms-react-seed/blob/7c57180ee581dda8d2336730655ccb5498eed8a2/src/index.tsx#L22

By removing this tag, I successfully prevented the Material styles from affecting the rest of my page.

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

Is there a way to format this into four columns within a single row while ensuring it is responsive?

I am working on a layout with a Grid and Card, aiming to have 4 columns in one row. However, the 4th column ends up in the 2nd row instead, as shown below: My goal is to align all 4 columns in a single row. Additionally, when viewed on a small screen, th ...

I need to fetch data from mongoDB by allowing the user to input a name into a search field, and then retrieve all documents that correspond to that search term

I am currently able to query the database by finding a specific key:value pair in the documents. However, I would like to enhance this functionality by allowing users to input their own search criteria as an argument in the function. Right now, I have hard ...

Monitoring changes in input can be a crucial step in any data analysis

Is there a way to track changes in input using backbone? How it can be achieved in AngularJs: <div ng-controller="W3"> <input type="text" ng-model="val" > <p>{{val}}</p> </div> I would like the value of the in ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

Execute Javascript to close the current window

When I have a link in page_a.php that opens in a new tab using target="_blank". <a href="page_b.php" target="_blank">Open Page B</a> In page B, there's a script to automatically close the tab/window when the user is no longer viewing it: ...

Using HTML and CSS to stack a DIV on top of another using z-index

I have 3 main layers on my website: 1) The main view with elements inside (#views in jsbin) - BOTTOM LAYER 2) An overlay (with a white background opacity of .8 #overlay in jsbin) - MIDDLE LAYER 3) A context menu (#contextmenu in jsbin) - TOP LAYER Wh ...

Ensure to wait for the user ID before accessing Firestore collections

Trying to wrap my head around rxJs and experimenting with using the where query in Firestore collection. However, I've run into an issue where the output of this collection is dependent on retrieving the user ID from Firebase Auth. Here's what I ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Focus on selecting the first child <li> element that contains an <a> tag within it

Struggling a bit with selecting only the first child within a li tag that contains a link. HTML: <ul class="dropdown-menu" role="menu" aria-expanded="true"> <li role="presentation" class="dropdown-header">Label</li> <li><a ...

Updating database with Ajax when the button is clicked

Seeking guidance with a project as I am still grasping the concepts of javascript and jquery. The goal is to update a database entry upon clicking a button, where the content of the button is fetched from the database. Initial step involves querying the d ...

Arrange Raphael Objects in Their Relative Positions

I've been experimenting with Raphael.js recently and I've encountered an issue related to the positioning of each Raphael object. My goal is to create multiple 'canvases' without having them overlap within a predefined div on the page. ...

Navigating through the directories in PUG using the absolute path

Referring to the docs for PUG (), it states: If a path is absolute (example: include /root.pug), it gets resolved by prepending options.basedir. Otherwise, paths are resolved in relation to the file being compiled. To clarify, I understand that this in ...

Changes to the parent state will not be reflected in the child props

When the child component PlaylistSpotify updates the state localPlaylist of its parent, I encounter an issue where the props in PlaylistSpotify do not update with the new results. I've been struggling to figure out what I'm missing or doing wrong ...

Using React Recharts: Can you show a chart within an email?

Our team is currently utilizing React Recharts for chart building within our application. Additionally, we have a specific need to include a chart in an email communication. To accomplish this task, we are leveraging a C# microservice operating within Ku ...

Heroku Internal Server Error with NextJs version 5.0.0

Below are the scripts that I am using: "scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js", "heroku-postbuild": "next build" }, This is the content of my procfile: web: npm start ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...

Managing font size in Material UI - Adjusting label text size in FormControlLabel

Is it possible to customize the font size of the label within FormControlLabel while utilizing React for Front End JS development? <FormGroup row> <FormControlLabel control={ <Checkbox onClick={() => onClick('r ...

Limited functionality: MVC 5, Ajax, and Jquery script runs once

<script> $(function () { var ajaxSubmit = function () { var $form = $(this); var settings = { data: $(this).serialize(), url: $(this).attr("action"), type: $(this).attr("method") }; ...

Align images to the bottom of the gallery only if their heights differ

I'm currently working on an image gallery project and have encountered a problem. When all the image labels are of the same length, they align perfectly. However, if the label is longer than one line, it causes the image to move up instead of creating ...

Deploying NextJS: Error in type causes fetch-routing malfunction

Encountering a mysterious and funky NextJS 13.4 Error that has me stumped. Here's a summary of what I've observed: The issue only pops up after running npm run build & npm run start, not during npm run dev The problem occurs both locally and ...