What is the best way to configure custom CSS styles in a React project?

I've been trying to position my Grid component from Material-UI, but so far, I haven't had any luck. What could be the issue here?

class Scene extends React.Component {
  render() {
    const mystyle = {
        backgroundColor: "DodgerBlue",
        position: "absolute",
        top: "125px",
        left: "125px",
        width: "100px",
        height: "100px"
    };

    return (
      <div className={mystyle}>
      <Grid container>
        <Grid item xs="2">
          <Board init={1} end={2}/>
        </Grid>
      </Grid>
      </div>
    );
  }
}
export default Scene;

https://i.sstatic.net/2FdDX.png

Answer №1

It appears that in your case, the issue lies with className={mystyle}. The variable mystyle is not a "className", but rather an actual "style" object. Try replacing className={mystyle} with style={mystyle}, this should work by converting those styles into inline styles within the div.

Regarding the question of "How to set custom CSS styles in React?", a simple search will yield numerous answers and articles on the topic. For example, you can check out this article, which covers (at least) 4 ways to apply styling in React:

  1. Using Css Stylesheets
  2. Inline styling, including actual inline styling as well as using an object (similar to what you attempted)
  3. CSS Modules
  4. Utilizing a css-in-js library like Styled-components to create "styled components"
  5. Exploring library-specific methods, such as turning a JavaScript object into a className using React Hooks (which may align with the approach desired, particularly the Material-UI framework)

Answer №2

One option is to pass it as a style attribute, or if you're considering using multiple classes, you can utilize "css-in-js" for styling your components. Learn more about this approach in the material-ui documentation.

import { withStyles } from '@material-ui/core/styles';

const styles {
   mystyle: {
        backgroundColor: "DodgerBlue",
        position: "absolute",
        top: "125px",
        left: "125px",
        width: "100px",
        height: "100px"
    }
}

class Scene extends React.Component {
  render() {
    const { classes } = this.props;

    return (
      <div className={classes.mystyle}>
      <Grid container>
        <Grid item xs="2">
          <Board init={1} end={2}/>
        </Grid>
      </Grid>
      </div>
    );
  }
}

export default withStyles(styles)(Scene);

You can also achieve a similar result using hooks:

// ...
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles({
  mystyle : {
        backgroundColor: "DodgerBlue",
        position: "absolute",
        top: "125px",
        left: "125px",
        width: "100px",
        height: "100px"
    }
});

function Scene () {

    const classes = useStyles();

    return (
      <div className={classes.mystyle}>
      <Grid container>
        <Grid item xs="2">
          <Board init={1} end={2}/>
        </Grid>
      </Grid>
      </div>
    );

}

export default Scene;

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

What is the correct way to align a shape with a border width in the center of its parent input button?

My newsletter subscription box features a form that spans the entire width of its parent element, causing the button to fill up all available space. To add a visual touch, I used the before CSS pseudo-element to create a small 'arrow' shape abov ...

How can I use map functions to change the border color of specific items when clicked?

I have an array filled with various data. Here is how my Array looks like, const faqData = [ { q: "How Can We Help You?", a: "Find answers to our most frequently asked questions below. If you can't find what you need, pl ...

How can I center two div buttons within a bootstrap column?

My issue is as follows: I currently have two circles stacked on top of each other, but I would like to position them side by side. Below is the HTML for the existing layout: <div class="col-lg-6"> <div class="page-scroll" style="text-align:c ...

Behold the magic of a three-column layout with sticky scroll behavior and an absolute

I am struggling with a layout that involves 3 columns, each with its own independent scroll. The first column contains an absolute element that should overflow on the x-axis, but I am having trouble getting the overflow-x:visible property to work when comb ...

Ways to adjust flex division to occupy the entire height of its container

https://i.sstatic.net/4YInI.png https://i.sstatic.net/hu8mG.png https://i.sstatic.net/Q51ha.png I am looking to activate an onClick event on the body where discussions and icons are located. While triggering onClick on the body itself poses no issue, I a ...

Design of website built on Bootstrap framework seems distorted on Firefox browser

I built this website with the help of Bootstrap and you can view it at js-projects. Everything looks great when I open it in Chrome or Safari, but there are weird white strips that resemble scroll bars when I view it in Firefox. Can someone assist me in ...

What is the best way to bring a JavaScript module into the public folder of a React

In my React project, I have a public folder with an HTML file and a simple JS file. Additionally, there is an src folder located outside the public folder. When attempting to import something into the JS file outside the public folder, such as: import Open ...

"Troubleshooting Bootstrap nav-pills' failure to update displayed content

I'm currently working on creating a dynamic navbar that updates the content based on which navigation pill is selected. For some reason, the content in my div.tab-content isn't changing as expected... Here is an example of the code I am using: ...

Limit the Datepicker in MUI (v5) to only accept two-digit years

I am currently using the MUI (v5) Datepicker for capturing user birthday information. The Datepicker has been localized to German language, resulting in the input format DD.MM.YYYY. However, many German users prefer using a shorter year format like DD.MM. ...

Exporting components in React allows you to make them reusable and

Currently, I am utilizing boilerplate code to create a chart with the Chartist library. The only alteration made was adding export before the class: import React from 'react'; import ReactDOM from 'react-dom'; import ChartistGraph from ...

Using React to send asynchronous state from a parent component to a child component following a fetch request within a functional component

I need help with passing an async state value from a parent component to a child component after updating the state with data fetched from an API call: Profile.js function Profile() { const { id } = useParams(); const [user, setUser] = useState(); ...

Retrieving the background image URL from inline CSS using jQuery

I'm looking for a link similar to url(img/bg/06.jpg), but when using jQuery, I get a longer link like url("file:///D:/WORKING%20FILE/One%20Landing%20Page/version/img/bg/06.jpg") https://i.stack.imgur.com/8WKgv.png Below is the code snippet in questi ...

Multiple images overlapping each other in a dynamic parallax effect

Despite my fear of receiving down votes, I have been unsuccessful in finding the answer to my question so I will proceed with asking it. I am attempting to replicate a parallax effect similar to the one showcased on this website, particularly the image of ...

Adjusting the width of a Material UI drawer: Tips and tricks

Currently, I am working on implementing the Material UI drawer and anchoring it to the top of my page. It is functioning correctly, however, I am encountering an issue where I am unable to adjust the width of the drawer. Despite trying to update the width ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

React-table fails to show newly updated data

I am facing an issue with my react-table where real-time notifications received from an event-source are not being reflected in the table after data refresh. https://i.stack.imgur.com/q4vLL.png The first screenshot shows the initial data retrieval from th ...

What is the best method for eliminating buttons and text in a row using CSS?

I faced an issue when trying to create a row, so I improvised with the following setup. However, I actually need a proper row layout for both the Google button and telephone number button. Here are my CSS snippets: .google-button { color: white; borde ...

I'm experiencing difficulty with the image path, as no images are visible on my Next.js application after deployment

As someone new to web development, I have encountered a perplexing issue that I just can't seem to resolve. Despite my efforts to find a solution online, I am now reaching out for assistance. I have developed the source code using Next.js v13.3, and ...

The Material UI list element fails to appear on the screen

I am encountering an issue where I am trying to display a Material UI list within a drop-down menu (using the Material UI drawer component) for mobile view, but the actual list is not appearing as expected. The code snippet for the list is as follows: con ...

The placeholder text color in MUI Textfield appears muted

I have been attempting to customize the placeholder color for MUI TextField. While I did manage to make the placeholder turn red with the styles I applied, the shade of red appears somewhat faded. How can I adjust the styling to make the placeholder colo ...