I have some issue using scss directly in material ui, because not all styles are applied. Tried to use makeStyle, but because I use class component, it gives warning about invalid hook call.
The style :
.table-header {
background-color: #005CAA; //only this style works
color: white;
font-weight: bold;
text-align: center;
}
I call in in TableCell component from Material UI
<TableCell className="table-header">Invoice Number</TableCell>
For the scss file, I import it in parent component App.tsx, or I need to import the file directly in the Table component? Thx
I follow the makeStyles approach as it's recommended way of overriding the material-ui styles, else you'd have to use !important in your css/scss files to override the material-ui styles.
https://mui.com/styles/basics/
// component file
import React from 'react';
import { TextLineStyles } from './styles';
export default function TextLine({ text }) {
const classes = TextLineStyles()
return <div className={classes.root}>
<div data-title="line" >
<div data-title="text">
{text}
</div>
</div>
</div>
}
// style.js
import { makeStyles } from "#material-ui/core/styles";
export const TextLineStyles = makeStyles(theme => ({
root: {
'& [data-title="line"]': {
borderTop: `1px solid lightgray`,
'& [data-title="text"]': {
color: 'red' // scss like nesting
}
}
}
}));
If you want to use CSS/SCSS class in MUI component, you should import the file directly in the Table component. But, it's not good to use SCSS with MUI component, you should use makeStyles or withStyles to style the MUI component.
I am not sure if it is the best practice, in fact thats why I ended up in this post.
Here it explain how to use scss with material-ui: https://www.markmakesstuff.com/posts/mui-css-modules
"Just install node-sass"
"if you're working with an app you initialized with a script like create-react-app, you are in luck. No webpack edits necessary. Just give your module a name that ends with ".module.scss""
OTHERWISE
2') You need to "make some minor edits to your webpack config"
"You can then import your module with a name then use that to refer to your classes when writing your fancy JSX"
I am trying to import styles from a .css file into a react js file using "import '../css/banner.css', with css-loader and style-loader installed and enabled. It should be the most direct and simplest method to import css in react, but the styles just won't apply.
I am trying to achieve this without using other libraries like styled-components or jss.
banners.css:
.headerItem{
width: 20vw;
float: left;
background-color: cadetblue;
margin: auto;
padding: 3em;
text-align: center;
}
Header.js
import React ...
import '../css/banners.css'
class Header extends React.Component{
constructor(){
}
render(){
return (
<div className={"header"}>
<HeaderItem/> //shown as an example, has className of "headerItem"
</div>
)
}
}
The problem is not relevant to wrapping curly brackets around the class name or not. I found out that in my webpack.config.js I had set the modules option in "css-loader" to be true, which led to the css-loader looking for modules.css files instead of .css files. Changing the modules option to false solved my problem. (If you are using css modules then remember to set the flag to the correct value!)
As a matter of fact, arguments to be passed onto a React component should always be wrapped in curly brackets, and even if you don't the compiler will automatically add them for you since every argument is treated as an object, which would then be collected and passed as props down to the Child Component.
Apologies for raising such a trivial and wrongly-focused question.
Try this one. Dont use {} in className
<div className="headerItem">
<SomeChild/> //shown as an example
</div>
The best and simplest way to include CS into your react project is;
rename your file to [FileName].module.css
import it into your project using import importedStyles from './[FileName].module.css
use it by calling the imported name . the css style you want to use. eg importedStyles.bodyStyle
rename bannerss.css to banners.module.css:
.headerItem{
width: 20vw;
float: left;
background-color: cadetblue;
margin: auto;
padding: 3em;
text-align: center;
}
Header.js
Call the css file into your project and use;
import React ...
import bannerStyles '../css/banners.module.css'
class Header extends React.Component{
constructor(){
}
render(){
return (
<div className={"bannerStyles.header"}>
<HeaderItem/> //shown as an example, has className of "headerItem"
</div>
)
}
}
This should work fine and its easy.
Reference: https://www.w3schools.com/react/react_css.asp
Let me know if this works!
Dont use curly braces , or best you can use styled components to give css property
I installed 'react app 2' as well as node-sass. It's working fine with SCSS. But I just want to know how can I create component specific SCSS like Angular (that will never be a conflict with other components SCSS)
Angular automatically add an attribute for ViewEncapsulation see below example
In angular, there is an option for
encapsulation: ViewEncapsulation.None (Use to disable CSS Encapsulation for this component)
enter link description here
I know the question is old, but it has no answer, thus I want to share this article. Alsomst does the trick, with the exception that it seems to does not have support for something like ::ng-deep
React doesn't have native component styles like Angular does because it aims to keep away from any functionality that could easily be handled by third-party packages. So you have two pretty simple options:
Use styled-components to create component-specific styles. This is a pretty straightforward package that allows you to define styles for each element within a component and you can even pass variables into the styles. It generates internal CSS (kept in <style> tags in the document head) which will take precedence over external styles by default. Example:
// MainComponent.jsx
import React from 'react';
import styled from 'styled-components';
const Title = styled.h1`
color: red
`
const MainComponent = (props) => <Title>Hello World</Title>
In each of your components, add a class or ID to the root element so that you can simply add that selector to the beginning of your SCSS to only style that specific component. Example:
// MainComponent.jsx
import React from 'react';
const MainComponent = (props) => (
<div className="main-component">
<h1>Hello World</h1>
</div>
)
// MainComponent.scss
.main-component {
h1 {
color: red;
}
}
Now only h1 elements in your MainComponent will be red.
//JS
import React from "react";
import "./yourComponentName.scss";
export default props => {
const { className, children, ...restOperator } = props;
return (
<a className={`yourComponentName ${className}` } {...restOperator}>
{children}
</a>
);
}
//yourComponentName.scss
.yourComponentName{
position:relative;
background:red;
/* your property and value use nesting*/
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
In the create react app documentation it says the App.css is imported in the App.js. Is there also a way to load the compiled css-file from a component?
// MyViewComponent
import styles from '../../App.css';
You can just import the css file like the below in your component
import './header.css';
Imagine your header.css file looks like
.header {
background-color: rgb(49, 118, 197);
height:100px;
border:10px solid red;
}
To use the style, you can use the class like ,
<div className="header">Hello World</div>
Hope this helps :)
For css files you can just import them like
import "../../App.css"
which will import all of the selectors & CSS rules within that file.
if you're trying to style individual elements within your component with something like:
<div style={myStyles.wrapper} />
then you'll need to export a JS object from a file
Ex:
export default {
wrapper: {
background: "red"
}
}
then you can import it and use it
import myStyles from "../myStyles.js"
<div style={myStyles.wrapper} />
I'm using React.js and want to change the background color of the entire page. I can't figure out how to do this. Please help, thank you.
Edit (Sep 2 '18): I have a project on GitHub that I'm linking here. I don't have this project online right now, but in the /client folder is the client server. Check it out. This is how I answered the question.
The simplest solution is a bit hacky, but you can use raw javascript to modify the body style:
document.body.style = 'background: red;';
// Or with CSS
document.body.classList.add('background-red');
A cleaner solution could be to use a head manager like react-helmet or next.js Head component.
import React from 'react';
import {Helmet} from 'react-helmet';
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<style>{'body { background-color: red; }'}</style>
</Helmet>
...
</div>
);
}
};
Some css-in-js also offers tools to manage global level styles; like styled-components injectGlobal.
In the end, there's a lot of tools providing cleaner ways to handle this. But if you don't want to rely on third party, the raw JS option might be good enough if you don't make it too interactive.
The simplest solution without doing anything fancy is to:
1) Open public/index.html
2) Add an inline style to your body like this:
<body style="background-color: red">
try this to your code
componentDidMount() {
document.body.style.backgroundColor = "red"
}
React Helmet (https://github.com/nfl/react-helmet)
I really found this library very helpfull. Really clean solution i would say.
Sample Usage:
import Helmet from 'react-helmet';
<Helmet bodyAttributes={{style: 'background-color : #fff'}}/>
The above solutions tell about adding the external library to give the required functionality but instead what you can do is just go to your Index.css file and inside the already written 'body' tag put "background-color: 'color'" and its done
The basic idea is to use the browser API in raw JavaScript without installing any packages. I don't recommend to use Helmet because it is unsafe to the life cycle of a class component.
// Update the document body background using the browser API
// in render() function for class component or directly in functional component
document.body.style.background = 'red';
Other application:
If you are constantly changing the body's background color, and you want to have the code to run on every render, following is an example. Be careful where you call the browser API.
For a class component, update it in componentDidUpdate().
import React from 'react';
class Example extends React.Component {
// ...
componentDidUpdate() {
// change background color with a random color
const color = Math.floor(Math.random()*16777215).toString(16);
document.body.style.background = color;
}
// ...
}
For a functional component, using Effect Hook useEffect(). You can look more into React Hook here.
import { useEffect } from 'react';
function Example() {
// ...
// Similar to componentDidMount and componentDidUpdate in class component:
useEffect(() => {
// change background color with a random color
const color = Math.floor(Math.random()*16777215).toString(16);
document.body.style.background = color;
});
// ...
}
If you want to change background color before the page loads you can do something like this.
import React, { useLayoutEffect } from 'react'
useLayoutEffect(() => {
document.body.style.backgroundColor = "red"
});
For further reference on useLayoutEffect check here
I just fiddled around with this for a bit. Simple solution for me, not entirely intuitive, all in public/index.html:
<html style="background-color: red">
that gets the bottom of the page, and a second entry:
<body style="background-color: red">
that gets you the top of the page ie. your react code.
Two entries for one problem but it's all in one file, needs no new libs and seems to work.
Please Don't need to install any packages is very easy and simple !
add
document.body.style = 'background: red;';
to your JS code or via CSS like below:
const Changebackground = () => {
const stylesObj = {
background: "green"
};
return ( <
div id = "hello-world"
style = {
stylesObj
}
className = "container" >
<
/div>
)
}
export default Changebackground;
//ReactDOM.render( < Changebackground / > , document.getElementById('App'));
.container {
position: fixed;
width: 100%;
height: 100%;
z-index: -10;
text-align: center;
transition: all 500ms ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>
please check this one to see how its easy !
https://codepen.io/farbod-aprin/pen/dadJyb
After some time scouring the internet, I found this solution on a now deprecated github repo:
document.body.style.backgroundColor = "INSERT_COLOR";
You can post it outside of your function (That's how I used it)
It worked for me in my project: https://github.com/antdke/styled-input-bar/blob/master/src/App.tsx
I needed it to color the background for the entire app.
Where I found the code snippet (At top of the README.md): https://github.com/happylinks/react-body-backgroundcolor
Hope it helps you all out like it helped me :)
You should have a root component (e.g., a div) that is affected by the color you want as the background. That's the react-way to think about it.
<div className ="bg-primary"> // this should cover everything in the background
<div className="container mx-auto bg-secondary"> // this could be a centered container that has a different color.
<MyReactComponent />
</div>
</div>
The style property is not writable in Typescript but setAttribute works okay. Just pop it in your App component. It may not be a good idea to have a random bit of styling outside of React's many other styling mechanisms, it might make it hard to find, but if it's what you need it's what you need. It's what I needed today anyway!
document.body.setAttribute('style', 'background: red;')
You can use a CSS module in React. Below is the Javascript code for a file named Home.js
import styles from './Home.module.css';
const Home = ()=>{
return(
<div className = {styles}>
</div>
);
}
export default Home;
And in a css module named Home.module.css (format is [name].module.css), put the following and your page will have a background colour of blue
body{
background-color: blue;
}
I faced this issue too and this is my solution.
body{
margin:0;
background-color:blue;
}
This was simplest solution for me:
// in your css file
.background-white {
background-color: white !important;
}
// in your react component
componentDidMount() {
document.body.classList.add("background-white");
}
componentWillUnmount() {
document.body.classList.remove("background-white");
}
Using componentWillMount did not work reliably. Using document.body.style did not work reliably either.
If you are using React with Bootstrap, just include a background-color Bootstrap class to the <body> tag, in the index.html file, like this:
<body class="bg-light">
You can choose other colors from https://getbootstrap.com/docs/4.3/utilities/colors/#background-color
In your react src folder you should have a custom.css file.
Add 'body {background-color: ; }' in that custom.css file.
By default, assuming you've used npx Create-React-app MyAppName your React app will have an index.css.
This contains css which controls the default grey background. Just edit this to what you require.
body {
margin: 0;
background-color: #3f3f3f;
}
create index.css file like this
body {
margin: 0;
background-color: rgba(0, 0, 0, 0.07);
}
Then import it in your index.ts file
import "./index.css";
Also keep in mind the background color property might get overwritten if you import other css files below
So your index.ts file look like this
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "bootstrap/dist/css/bootstrap.css";
import "./index.css";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
This works for me as long as my body's data has content in it
body { background-color : rgba(235,232,232,0.767); }
Similarly, you can alter the root tag as well.
#root{ background-color: rgba(235, 232, 232, 0.767); }
Make a wrapper componenet with an id like "wrapper" and then create a style with the color state:
getInitialState: function () {
return { color: "white" }; // Set your color for initial state.
},
changeColor: function () {
this.setState({ color: "black" }); // Set your changed color.
},
render: function () {
var style = { backgroundColor: this.state.color };
// The wrapper (root) component
return (
<div id="fullscreen" style={style}>
<a onClick={this.changeColor}>change</a>
</div>
);
}
The result should be something like:
<body>
<div id="fullscreen" style="background-color: YOUR CUSTOM COLOR">
<a onclick="THE REACT FUNCTION"></a>
</div>
</body>
It's been a while since I asked this question. What I've started doing since then is using Facebook's create-react-app setup, and editing CSS files directly.