How to use Stylesheets on React Server Side Rendererd App? - css

I am trying to convert my ReactJS application to Universal App with server-side rendering, but there is something that I don't understand. What is the best way to use and import styles to my components? Can I just import external stylesheet in HTML and use this all over my components? or import specific stylesheet to every component and use it as separate variables like this :
import s from './about.css';
export default class About extends Component {
render() {
return (
<div>
<div className={`${s.divone} row`}>
<span>Hello world</span>
</div>
<div className={s.divtwo}>
<span>bye world</span>
</div>
</div>
);
}
}
with the second approach, I have noticed that every time I do refresh my page, the styles are kinda too slow to load, and for one second I see my page without any CSS, and then I see my full page with CSS. There is any way to bypass that without external and global stylesheet? Like for example, Airbnb does. Maybe with some way to wait until all styles are loaded?
Also after I moved my app to server-side render, I get some strange warnings like this :

You can use classnames, a simple and small JS library to import and use css in your react components:
import styles from './css/yourcss.css'
import classnames from 'classnames/bind'
const cx = classnames.bind(styles)
// use in react component
<div className={cx('mydiv')}></div>
cx can have any JS expression inside it or just plain class name from css you have imported styles from.

Related

How to display FontAwesome icons in react HTML set with dangerouslySetInnerHTML

I have a react.js web app and a REST API that returns a chunk of raw HTML (not a complete page). I get the HTML by scrapping a website and grabbing a piece of the markup using cherrio.js. In the developer tools, the response itself is the markup. I use the dangerouslySetInnerHTML={{ __html: htmlMarkup }} element attribute so that react knows to display it as the inner HTML.
However, I need to insert some FontAwesome icons into it. I've tried both straight HTML using, <i class="fa-solid fa-star-sharp"></i>, and the react version, <FontAwesomeIcon icon="fa-solid fa-star-sharp" />. Both of these come straight from the FA docs.
Within my component that inserts the HTML I import the FontAwesomeIcon component (import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";) and also import the FontAwesome CDN CSS file using a SASS file that I import into my root JS file. I also import the #fortawesome/fontawesome-svg-core/styles.css file.
SASS file: fa.scss
#import url(https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/fontawesome.min.css);
index.js
import 'fa.scss';
However, after I load the HTML markup, insert my icon, and then set the dangerouslySetInnerHTML attribute, my icon doesn't display.
What am I missing?

CSS file loading order in VueJS

I am relatively new to VueJS, and currently I run into an issue with styles related to semantic ui. The problem is that semantic ui's styles overload custom styles. And the CSS developer told me to make sure that semantic ui's css is loaded before all other css files.
Notably, my current code looks like this:
App.vue
<template>
...
</template>
<script>
export default {
name: "App",
};
</script>
<style>
#import "styles/my_custom_css.css";
</style>
main.js (only relevant part, might not be a working code)
import Vue from 'vue';
import App from './App.vue';
import SuiVue from 'semantic-ui-vue';
import 'semantic-ui-css/semantic.min.css';
Vue.use(SuiVue);
new Vue({
el: '#app'
render: h => h(App)
});
I wonder how to ensure that semantic.min.css is loaded before styles/my_custom_css.css. Maybe I need to reorganize the code structure ?
you could import it in the same place, but before your own .css-file
// App.vue
<style>
#import 'semantic-ui-css/semantic.min.css';
#import 'styles/my_custom_css.css';
</style>
And the CSS developer told me to make sure that semantic ui's css is loaded before all other css files.
He is right. because css stands for cascading style sheet. the styling is adjusted line by line.
Whatever is called first will be adjusted first. So the last line of the styling will always be the one actually used. The term cascade gives you the hint. If you put your css before the semantic one, the semantic one overwrites your css and vice versa.

Using bootstrap in web components shadowDOM

What's the easiest way to use a large css library (like bootstrap) in web components / shadowDOM app using LitElement?
Tried the following:
Use the link tag within the component. Works, but creates FOUC (flash of unstyled content).
Render everything to Light DOM (I'm using LitElement and they have a createRenderRoot() override. Works as well, but as the app gets more complex, maintaining component document isolation would be nice.
Looking for the simplest way to just use boostrap in this setting.
LitElement's recommended way to add styles to components is via the styles property. Loading external .css files this way is not straightforward, but there are some solutions.
The import way
If your definition of "simplest way" comprises using transpilers or module bundlers then you can use non-js inlined imports to accomplish something like the following:
import bootstrap from './path/to/bootstrap.css';
// ...
class MyElement extends LitElement {
static styles = bootstrap; // If your build system already converted
// the stylesheet to a CSSResult
static styles = unsafeCss(bootstrap); // If bootstrap is plain text
}
There are many plugins dedicated to this: see for example babel-plugin-inline-import, rollup-plugin-lit-css, rollup-plugin-postcss-lit, webpack-lit-loader.
The wrapper way
If you want to keep things (almost) buildless you can write a simple postinstall script that generates a .js file that exports the lit-ified styles:
// bootstrap.css.js
import {css} from 'lit-element';
export const bootstrap = css`
<bootstrap here>
`;
// my-element.js
import {bootstrap} from './bootstrap.css.js';
class MyElement extends LitElement {
static styles = bootstrap;
}
About Shadow DOM
If you want to use Shadow DOM you'll have to import the library in every component that needs to use it, even nested ones. This is not as onerous as it seems thanks to Constructable Stylesheets, used by Lit under the hood; think of it as a way for components to join style contexts more than a replication of identical stylesheets. Also, to keep things organized you can create a "base" component that imports bootstrap and extend it wherever needed:
import bootstrap from 'path/to/bootstrap.css';
export class BaseElement extends LitElement {
static styles = bootstrap;
}
class MyElement extends BaseElement {
render() {
// Bootstrap is ready to use here!
return html``;
}
}
Lit documentation about style sharing: https://lit.dev/docs/components/styles/#sharing-styles

React and CSS Styling

In my page, I have to use two react components
Component1 and Component2
Page1 code
<Component1/>
<Component2/>
All the styling for components would come from the component CSS files. But for the page layout, I have page1.css
I would write selectors and classnames and define styles for page1.css.
There could be many pages and different layouts with similar classnames, how can we control the behavior of not having overriding styles.
You can use CSS module to apply the style to each component, it works so well, easy to manage code and it is local selector as well, so there is no conflict between 2 component.
Project tree will be like:
Component:
Button
Button.js
Button.module.css
Form
Form.js
Form.module.css
Avatar
Avatar.js
Avatar.module.css
Each component will have a unique css file to come with, so it is very easy to maintain the code when scaling up.
How to use:
create-react-app
Install css-loader
Create css file with add-on module at the file name ex: styles.css => styles.module.css
4.Import styles to component:
import styles from './styles.modules.css'
5.Add classname to JSX tag
<div className={styles.header}> Hello world</div>
Start styling your component by using normal CSS
You can use css specific to that component only:
page1.js
import './page1.css'
// page1 component
I suppose page1 component folder structure like:
page1/
page1.css
page1.js

React - Child componet stylesheet overwriting other child's stylesheet

I'm trying to apply separate styleSheets for every child component by importing different styleSheets in different components but fails to achieve this as styles are being overwritten.
Sample Code: Stackblitz
childa.jsx:
import React from 'react';
import "./childa.css"
export default () => <h1>Child A!</h1>;
childa.css:
h1 {
color: blue;
}
childb.jsx:
import React from 'react';
import "./childb.css"
export default () => <h1>Child B!</h1>;
childb.css:
h1 {
color: red;
}
This is just a sample code. Need solution for a project having large styleSheets.
Based on your clarification in one of your comments:
The thing is I'm converting a project from angular to react and all
the css is already written so I can't use inline style. Is there any
way in which I don't have to rename all the css classes in all the
stylesheets?
Short ans: You can't achieve that as of now.
This article explains all the different ways to style react components. In your case, the best that you can do is use css modules and rename generic classes like h1 to .h1.
Check this great article about css modules: Modular CSS with React.
Note: css modules are not available in create-react-app. If you must use it here's an
article on how to use CSS Modules with create-react-app.
I think this is caused by ther order of the imports.
In your parent component you have something like
import React from 'react'
import ChildA from './ChildA'
import ChildB from './ChildB'
This means that in the compiled code you'll have the two stylesheets imported one after the other, and the second h1 rule will overwrite the first
You should use classes for your components, or use inline style
Importing a css does not wrap it in the scope of the component is just a straight import into the DOM. In order to mantain a separation of components styles you have to approach with another solution, as styled-components.
This may not work for your entire application, but I fixed it by applying a class to the element (.childA and .childB). This solved the problem.
export default () => <h1 className='childB'>Child B!</h1>;

Resources