How to use the <style> balise in React file - reactjs

For a Quick demo purpose, i need to get the actual <style> balise from a page that already exist.
I know that this is not something to do, it's only for a demo.
I have a huge <style> balise to integer into a react app. I just want to copy paste in and make as little change as possible.
I've seen that :
<style>
{'\
div{\
background-color:red;\
}\
'}
</style>
from here : React JSX Style Tag Error on Render
is working but this need to edit all line of my balise and i don't
have the time for that.
I also tried this :
https://medium.learnreact.com/the-style-tag-and-react-24d6dd3ca974
But unfortunately it's not working :/
I'm looking for a quick solution where i only need to edit the beginning and the end of my <style> balise.
Thanks in advance to the community

You can use a template literal.
const CSS = `
div {
background: purple;
color: orange;
}
`;
const app = (
<div>
<style>{CSS}</style>
Hello, world!
</div>
);
ReactDOM.render(app, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>

I understand you have a non react project with its styles and you are making it react, but you want to keep the css. If that is the case, I recommend the following:
1 - get the original tag, place it to a css file, and import it into your project's base html, this way you still have your styles whitout doing anything to react
2 - get the original tag, place it into a css file, and import it using javascript/webpack
import styles from './styles.css'
3 - if you still want to place a style tag in react in a similar fashion, I recommend you placing all the style css using the character ` to define de string in the following way (ECMAScript 2015) (the character ` is not the same than ' and it lets you use several spaces and even variables inside. Defining a string like this is called a template literal):
render(){
let myCss = `
div{
background-color:red;
}
`;
return (<style>
{myCss}
</style>)
}
4 - using "styled components". They are designed to make it easier to use css in react. Although they are intented to style a component, you also can do acopy paste of a whole css style inside one of the components. So, as long as all your react elements are children of the specific styled component you are using, it will use those styles. So you can perfectly do the following:
const styled = require('styled-components'); // or import styled from "styled-components";
let Wrapper = styled.div`
div{
background-color:red;
}
`;
class MyReactProject extends React.Component {
/** your react code **/
render(){
return (
<Wrapper>
{ /* your react code */ }
</Wrapper>
)
}
/** your react code **/
}
using styled components you can do a quick fix for the moment, and it will be easy to do a full styled components migration in the future (you only have to transform each of the base tags of your react project into styled components)
link to styled components

Related

How to use multiple css files for react pages?

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).

How to override CSS class with Styled-Components

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/

Styled components - Correct way of approach

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!!!

CSS for ReactJS - Referencing a div works fine, referencing a className does not

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">

How do I change the background color of the body?

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.

Resources