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:

https://i.sstatic.net/R0kj9.png

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:

https://i.sstatic.net/6UApn.png

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

In the production and development environments, the interpretation of CSS classnames is being rearranged

Currently utilizing create-react-app v2. I've encountered an issue with a component that has multiple classnames: "x15 x14 login-form__field". Strangely, in the production build, the order of '.x14' and 'login-form__field' seems t ...

What is the best way to trigger a JavaScript function to execute as soon as the innerHtml has been modified via Ajax

Utilizing Ajax to dynamically update the content of a div upon clicking a link is my current project. I am seeking guidance on how to call a JavaScript function once the file has been retrieved from the server and the div's content has been replaced. ...

Information submitted through an ajax request does not get saved in the $_POST array

After successfully executing an AJAX request using GET, I decided to try POST this time. However, when attempting to send data, a baffling error message appeared in the console - NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 'JavaScript component does ...

The issue of page content failing to refresh when loaded using AJAX technology

My script utilizes AJAX to dynamically load specific pages on a website. These pages display information that updates based on the current time. However, I have encountered an issue where the page content remains static when loaded through AJAX, almost as ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

Encountering a 'TypeError: app.address is not a function' error while conducting Mocha API Testing

Facing an Issue After creating a basic CRUD API, I delved into writing tests using chai and chai-http. However, while running the tests using $ mocha, I encountered a problem. Upon executing the tests, I received the following error in the terminal: Ty ...

Formik UI validation for Material-UI React radio buttons

I have successfully implemented formik with Material UI React form components, particularly the TextField component. Here is the code snippet for reference: <TextField id="firstName" name="firstName" ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

Performing a POST request using XMLHttpRequest with parameters in an asp.net environment

I am working on utilizing a javascript XMLHttpRequest object to send a post request to my action method. Here is my current setup: xmlhttp.open('POST', '../Employees1/HandleFileUpload', true); My action method does not currently take ...

What could be causing my node.js postgres function to return undefined even though I verified the value is displayed in the console?

Currently, I am in the process of developing a node.js application with a PostgreSQL backend. I have implemented a pool of connections and made an INSERT query to the database where I anticipate the last inserted ID to be returned. However, while the query ...

The state update does not seem to be affecting the DOM

I've implemented this component in my React app. It updates the state every second, but oddly enough the value <p>{this.state.time}</p> is not changing as expected. When I print the state value, it does change every second. import React f ...

The container in Bootstrap's CSS now appears when the navigation bar is present

Experiencing a minor issue here. I am attempting to create a layout with a navigation positioned in the top right corner, and the main content contained within a separate container below it. The problem I am facing is that the content container seems to b ...

Optimize the layout with Grid CSS to allow the last two items to dynamically occupy

I've been working on a layout that looks like this: X X X X X X X X A B Currently, I have used grid-template-columns: repeat(4, 1fr); to define the columns. However, what I actually want is for the last two items to take up the full width of the rem ...

Enter information to accompany your images in the description box

After browsing through numerous websites tonight, I stumbled upon this code. My goal is to create a photo upload page on Google Drive and set up a dropbox for it. I'm facing an issue where the information inputted into my placeholder box (city and ye ...

What is the best way to integrate LESS css into a Reactjs application?

I am looking to incorporate LESS into my React app, but I have been unsuccessful in finding a solution through Google. As a newcomer to ReactJs, I lack deep knowledge and would greatly appreciate guidance on installing Less. If anyone is able to help me ...

Integrating Whatsapp cloud API with a React web application allows for seamless communication between

I'm currently in the process of integrating my web application with the WhatsApp cloud API. While I've had success sending test messages, I am now looking to incorporate variables as outlined in the API documentation. However, I seem to be encoun ...

The dynamic text feature in my Angular Material gridlist functions perfectly in CodePen, however, it fails to work when

I have enhanced the Angular material gridlist demo by incorporating static and dynamic texts into the grid tiles. While this modification works flawlessly on Codepen (see my provided link), it does not function properly when deployed on my server. The sta ...

Troubleshoot Node.js server-side rendering in Visual Studio Code

Debugging an SSR React application on the server side has been a major struggle for me. Our team is working on developing a new app from scratch, and with the project being so large, debugging the code is crucial. Here's the webpack configuration for ...

Discover the flawless way to transmit client geolocation to a server. Encounter an intriguing hurdle: Unable to access undefined properties (specifically 'loc') while reading

I encountered an error that says "TypeError: Cannot read properties of undefined (reading 'loc')". This error was triggered when I attempted to pass the user's location to a server through a POST request. In my HTML file, I have included th ...

Using HTML and C# to Deliver Emails

I've encountered a challenge with my HTML page that includes a textbox for users to input their email. When the submit button is clicked, an email should be sent to a specific email address defined in the code, and a pop-up box indicating "Email Sent" ...