Im building a react application which has two pages(two react components) so far. My main issue here is that for each component i want there to be an external css file for it, but once there are two css files one files over writes the code in the other. For example, I have a homepage class which has some html code and is being routed to by the App.js file. I want to style my homepage component with a css file called home_style, this works fine if there is only one css file. Once i create another css file for that for my other component, it overwrites the code for the first css file(home_style) and ends up being applied for both my components. I had the idea of having all the code in one css file and set ids for each html component to be able to reference it properly, but i want to know if there is a better way to accomplish this.
Importing different css files into your js file doesn't mean it will only affect this js file only. In React, A css file is global, so you need to encapsulate your css with a parent :
// component1.js
const Component1 = () => {
return (
<div className="component1">
<span className="red">This is the component 1</span>
</div>
)
}
// component2.js
const Component2 = () => {
return (
<div className="component2">
<span className="red">This is the component 2</span>
</div>
)
}
Here I use the same class red in my two components. So in my css, if I want these same classes to do different things, i'll need to encapsulate it (as you said) :
//component1.css
.component1 .red {
color: red;
}
// component2.css
.component2 .red {
background-color: red;
}
Importing my css files or just writing this in a global css file will work, but if you are looking for some other solution, you can ahve a look at Styled components or JSS (These are just examples, there is multiple solutions to manage css in React, like simply using SCSS for easier encapsulation).
I want to override ant-tooltip-inner css class using Styled-Components.
Using normal import './Tooltip.css' everything works as intended.
// import './Tooltip.css'; // Overrides
const StyledLayout = styled.div`
// Doesn't Work
&.ant-tooltip-inner {
background-color: palevioletred !important;
color: white !important;
}
// Works on other CSS class
// default is light-blue - check Sidebar menu item in sandbox
.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {
background-color: purple;
}
`;
function CoolTooltip() {
return (
<StyledLayout>
...
</StyledLayout>
);
}
My goal is to override all tooltips coloring in my project (ant-tooltip-inner).
In this sandbox, all tooltips (of the Sidebar and Tooltip) need to be styled, uncommenting import "./tooltip.css"; will work.
Tooltips, Modal or similar components are rendered outside your SPA to improve the render performance of component tree.
Screenshot for same.
In your case you're trying to style a single instance of a component which will NOT work via local styling. You may refer to antd docs to do so or you may override it globally ( css file or any other way as docs say).
I already trying to override css of Modal from antd using styled-components, but still doesn't work as Kushalvm said above. I can override using pure CSS with className property from Modal.
See property API of antd Modal here --> https://ant.design/components/modal/
I am using styled components in my project.
Consider the following piece of code
import { Footer, FooterLeft, FooterRight, NavLink } from './footer_styles';
const FooterView = ({ prop }) => (
<Footer className="row">
<FooterLeft>
©Sample company, LLC
</FooterLeft>
<FooterRight>
<NavLink to="#" className="footer-link">Privacy Policy</NavLink>
<span className="separator"> | </span>
<NavLink to="#">Terms & Conditions</NavLink>
</FooterRight>
</Footer>
);
So i have the following questions.
1) Can i use bootstrap classes in styled components like what is shown in the code? Is this the correct approach? If not, how to use bootstrap styles along with styled components?
2) Do i need to create a component for each element in dom? For example, in the code that is shown, there is a span tag with class name "separator" for which the styles are added as follows
export const FooterRight = styled.div`
.separator {
float: left;
}
.footer-link {
margin-left: 0px;
}
`;
Is this approach correct? or
Do i need to create a separate component for separator?
I am a bit confused here. Any help would be appreciated.
You can use bootstrap class for style your component, it is nothing wrong. But it better if you use the React Bootstrap, library optimize for React. For example, the drop-down button you can use bootstrap class because it will use Jquery to execute the animation. But you shouldn't do it because Jquery manipulates the real DOM, React manipulate the virtual DOM so it is not good for performance.
You can read more here: https://reactjs.org/docs/integrating-with-other-libraries.html
The answer still yes, with the class to style the component, should use it to reduce the time for coding, with anything related to Jquery, just use the React Component.
I suggest you use the reactstrap, pretty similar to Bootstrap: https://reactstrap.github.io
Another thing, there is many ways to style component, but I am using CSS module, just need to create a CSS file with add-on module of the file name like this:
styleComponent.css --> styleComponent.module.css
And then import to your project:
import styles from './styleComponent.module.css'
And then you can style your component with normal css:
<div className={styles.separator} > Hello World </div>
In styleComponent.module.css:
.separator{
height: 20px;
background: black;
}
.separator:hover{
background: white;
}
It is more easy to manage your project because every single component it has a CSS file to go with it and the className is unique mean locally, Webpack will automatically convert the className 'separator' to '2djfas_separator' that will solve your problem with naming class in CSS.
Hope it helps a little bit for your project!!!
My CSS files work fine when I just use the element names like this:
div {
background-color: blue;
}
But when I use className to identify that div, the CSS is ignored, like this:
.containerInner {
background-color: blue;
}
Here is the js file, so you can see how I'm using className:
import React, { Component } from 'react'
import styles from './Game.css'
import GameContainer from './GameContainer/GameContainer.js'
class Game extends React.Component {
render() {
return (
<div className={styles.containerOuter}>
<div className={styles.containerInner}>
<h1 className={styles.header}>MEMORY</h1>
<GameContainer />
</div>
</div>
)
}
}
export default Game
Notes:
1. I am using create-react-app.
2. I am not using modular css like sass. I'm just using raw css.
3. This is a problem throughout my entire project, not just a couple files
4. There are no error messages in Chrome, or in the terminal
This is the same issue on Stack Overflow, but it does not appear to have been resolved on the thread, and the comments did not lead me to a solution. CSS class selector styles not being applied in React Project
Any ideas? Thanks in advance
If you want to apply a class name to a class, just apply the name. Class names are strings, not objects;
<div className="containerInner">
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.