inline style vs className in Componet context - css

Hello I try to understand when it's necessary to use inline style instead className in this case. I take a long time to solve my problem of translation. At the beginning I want to translate component by using classNameand that's don't work. it's very weird because in my point of view there is no reason that's happen. So I figure there is something wrong in my code, but what... I have not yet found. So I finish trying to translate by using a inline style. Miracle, that's work fine.
My question is why ?
Work well
export function Content() {
return (
<div style={{transform: 'translateY(100px)'}}>
<Test/>
<Footer />
</div>)
}
don't work
export function Content() {
return (
<div className={container_content}>
<Test/>
<Footer />
</div>
)
}
css
.container_content {
transform: translateY(100px);
}
Nota bene :
The problem is not from the method. To use className in my jsx
must be like that:
import { container_content } from "./test.module.css";
and next
<div className={container_content}><div>
So this part of code is good, the issue seems to come from elsewhere...

What's happening is that when you use the inline style you are passing an object that includes the styling for that component. When you use the className you need to pass in a string for the class you want to use. Right now you are passing a variable name. Either of these works:
<div className={"container_content"}>
OR
<div className="container_content">
If you think about it in regular html you would do
<div class="container_content">
EDIT: Given your updated question, you should just import the css file with:
import "./test.module.css"
and then use the solution I mentioned.

inside the js file, you need to import the CSS file like this
import " css-file-dir";
and then you can Reference to the CSS classes inside your component as a string
example :
className="container_content"

Related

Use SASS subclasses in React

My SCSS code :
.motherClass {
...
.subClass {
...
}
}
My TSX code :
return <div className={styles.motherClass}>
<div className={ ??? }>
...
</div>
</div>
In order to apply the subClass class to the child HTML element, how one would proceed ?
I have tried with
className="subClass"
className={styles.motherClass.subClass}
But none seems to work. Is there a way to do it ?
(It seems obvious, but I would like not to escape the sub class from the mother class for encapsulation reasons, so this solution is not on the table)
className={styles.subClass}
When using CSS modules, each class created in CSS/SCSS file is available as a property on the exported object.
Nesting has no effect on that, it only affects resulting selectors.

use Animate.css in ReactJS with react-animated-css

I am trying to implement Animate.css in React and throughout my researches I found the package react-animated-css which seems to be quiet straightforward, however I couldn't make it work.
In the documentation (if it's possible to call that a documentation) it's been said that the user should include the Animate.css in the HTML page, I didn't do that, since I am working with React and there is no HTML page, but I installed animate.css through npm.
Here follows a sample of my code:
import {Animated} from 'react-animated-css'
class ComponentTest extends Component {
render () {
return (
<div>
<Animated
animationIn="fadeInDown"
animationOut="zoomOut"
animationInDuration={1000}
animationOutDuration={1000}
isVisible={true}
>
<h1 style={{backgroundColor: 'red'}}>TESTE 1</h1>
</Animated>
</div>
)
}
}
I've also tried to set isVisible dynamically using a state, but without any success:
import {Animated} from 'react-animated-css'
class ComponentTest extends Component {
state = {animacao: false}
toggleAnimation = () => {
let animacao = !this.state.animacao
this.setState({animacao})
}
render () {
return (
<div>
<Animated
animationIn="fadeInDown"
animationOut="zoomOut"
animationInDuration={1000}
animationOutDuration={1000}
isVisible={this.state.animacao}
>
<h1 style={{backgroundColor: 'red'}}>TESTE 1</h1>
</Animated>
<button onClick={this.toggleAnimation} >Animação</button>
</div>
)
}
}
When I inspect my component I see that the classes are being applied in both cases:
Here is the page of the package: https://www.npmjs.com/package/react-animated-css
Any idea what I am doing wrong?
P.S. Using this package is not a must, I am completelly open to suggestions.
If you are using create-react-app just import animate css like this import 'animate.css' in your App.js file. I hope it'll work for you.
I don't know you might have got the answer till now but it's <Animate></Animate> instead of <Animated></Animated> in your ComponentTest. It might have been 'Animated' in previous versions which I am not aware of. However, you can check it here. https://www.npmjs.com/package/animate.css-react

Add className attribute to dangerouslySetInnerHTML contents

How to specify className attribute for div which contains 'hello world':
<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />
One way is to set is to outer div like so:
<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} className='class-name'/>
and then in css style the child:
.class-name div {
(css stuff here)
}
But I want to set className directly to the div with 'hello world'
EDIT: Adding class name to injected html does not solve the problem, for example:
let content = '<div class="class-name">hello world</div>'
<div dangerouslySetInnerHTML={{__html: content}}
does not work, because in case same content is used many times then CSS collisions occur (I am using style-loader with CSS modules on)
I came across this question after 2 years and I wanted to achieve the exact same results. I didn't find any accurate answers here but I came up with a solution thanks to #jash8506 due to the brilliant answer to this question.
We have to utilize two react hooks
useRef
useLayoutEffect
According to the documentation basically, useRef can be used to access the DOM elements in React and useLayoutEffect can be used to read layout from the DOM and synchronously re-render.
We can access the firstChildElement in the container div and add classes to it's classList
Here is how the completed code looks like
const containerRef = useRef();
useLayoutEffect(()=>{
if (containerRef.current){
containerRef.current.firstElementChild.classList.add('class-name');
}
});
return (
<div ref={elRef} dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />
)
<div className="post-excerpt" dangerouslySetInnerHTML={{ __html: post.excerpt}}/>

Styling from separate CSS files not applied with new components

I have been trying to build a small project with React for the past few days and all went great until today. For some reason, no CSS is applied to new components! All the CSS that worked before is still up and running but if I'd add something like a div in between an already existing div, the new div will not pick up any CSS!
Example:
<div className="DivStyle"> // Styling applied!
<div className="DivStyle"> </div> // Styling completely ignored!
<div>
It is probably worth mentioning that I am still able to style the components inline.
Also, looking at the sources in Chrome, the styles are uploaded!
Here is my concrete example:
import '../styles/drawers.css';
class BottomFilterDrawer extends React.Component<IBottomFilterDrawerProps, IBottomFilterDrawerState> {
...
public render() {
return(
<Drawer
open={this.state.isOpen}
anchor="bottom"
// tslint:disable-next-line jsx-no-lambda
onClose={() => this.toggleDrawer(false)}>
<div className="BottomDrawerContainer" style={{margin: "10px"}}> // Styling for "BottomDrawerContainer" class not applied!
...
</div>
</Drawer>
);
}
}
The CSS file:
#BottomDrawerContainer {
margin: 10px;
}
I am certain that the import path is correct, Typescript wouldn't even let me run it if it weren't.
You are applying css for class not for id. So your css must be like below.
.BottomDrawerContainer {
margin: 10px;
}
if you want to apply for inner div.
.DivStyle .DivStyle {
//style for inner div
}
do not use again same id, React create error and if show any error first you solve error otherwise browser not show anything

Is it possible to apply dynamic style as string in Angular?

I have a <span> that I want to apply dynamic style to.
Style is stored in a css-like string variable and can be arbitrary e.g.
myStyle = 'color: white; font-weight: bold;'
or
myStyle = 'background-color: red;'
I expected it to work like
<span style="{{myStyle}}">
but it didn't.
I tried different options but none seem to work for me for different reasons:
I can't put styles in a .css file and use class names because style is coming from server in the form of aforementioned string
Using [style.color] etc. doesn't suit me because I don't know what the style can be
Using [ngStyle] doesn't suit me because it expects object like {'color': 'red', 'font-weight': 'bold'} and I only have string
The reason I have a style stored in a string is because I need to apply it in HTML generated on the server where I simply pass that string to a placeholder variable in a velocity template.
I am almost confident that it can't be done the way I want but probably I am overlooking some solution.
All you need is DomSanitizer and bypassSecurityTrustStyle
Component side :
import { DomSanitizer } from '#angular/platform-browser';
constructor(private doms : DomSanitizer) {}
newStyle = 'background-color:red';
safeCss(style) {
return this.doms.bypassSecurityTrustStyle(style);
}
Template side :
<p [style]="safeCss(this.newStyle)">
Start editing to see some magic happen :)
</p>
WORKING DEMO
Angular provides the DomSanitizer service which can convert strings into style objects. I think this is exactly your case.
constructor(private sanitizer: DomSanitizer) {
}
sanitizeStyle() {
return this.sanitizer.bypassSecurityTrustStyle('background-color: red');
}
<span [style]="sanitizeStyle()">
I think I will go the way of converting the incoming css string into a style object and then applying it to <span> using [ngStyle]

Resources