wrapped in a useEffect hook and add a state value that is set to true after the stylesheet is appended to the document head.
const [isLinkElementLoaded, setLinkElementLoaded] = useState(false)
useEffect(() => {
const linkElement = document.createElement("link");
linkElement.setAttribute("rel", "stylesheet");
linkElement.setAttribute("type", "text/css");
linkElement.setAttribute(
"href",
"//fake.net/thirdpartylibrary.js/latest/thirdpartylibrary.min.css"
);
document.head.appendChild(linkElement);
setLinkElementLoaded(true)
}, []);
return (
<>
{isLinkElementLoaded && <div>Styled Component</div>}
</>
)
Answer from hustle100 on Stack OverflowVideos
wrapped in a useEffect hook and add a state value that is set to true after the stylesheet is appended to the document head.
const [isLinkElementLoaded, setLinkElementLoaded] = useState(false)
useEffect(() => {
const linkElement = document.createElement("link");
linkElement.setAttribute("rel", "stylesheet");
linkElement.setAttribute("type", "text/css");
linkElement.setAttribute(
"href",
"//fake.net/thirdpartylibrary.js/latest/thirdpartylibrary.min.css"
);
document.head.appendChild(linkElement);
setLinkElementLoaded(true)
}, []);
return (
<>
{isLinkElementLoaded && <div>Styled Component</div>}
</>
)
Try inside your component:
import React from 'react';
import './style.css';
...
You will need to add css-loader and style-loader to your dev dependencies in package.json
Link to webpack docs: https://webpack.js.org/concepts/loaders/#using-loaders
The way I do it (ex: import fonts from fonts.com) :
- create a css file,
- import external css in local css file
- import local css file in js
The best way I've found to use styles in react to avoid that type of problem is the use of styled-components (23k+ stars on github)
Example of styled-components usage:
const Button = styled.a`
/* This renders the buttons above... Edit me! */
display: inline-block;
border-radius: 3px;
padding: 0.5rem 0;
margin: 0.5rem 1rem;
width: 11rem;
background: transparent;
color: white;
border: 2px solid white;
/* The GitHub button is a primary button
* edit this to target it specifically! */
${props => props.primary && css`
background: white;
color: palevioletred;
`}
`
render(
<div>
<Button
href="https://github.com/styled-components/styled-components"
target="_blank"
rel="noopener"
primary
>
GitHub
</Button>
<Button as={Link} href="/docs" prefetch>
Documentation
</Button>
</div>
)
Ref: https://www.styled-components.com/
External CSS
If you are using external css you can parse it with:
import { css } from "styled-components";
// Css loaded as string and passed to css method of styled-components
export const borderBottom = css`
&:after{
content: "";
display: block;
height: 3px;
width: 200px;
background-color: ${props => props.color || "black"};
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
`;
Be aware that if you want to pack your css as string an edit to your webpack config may be needed.
Another way to import existing styles in styled-components
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Styled from "styled-components";
const fetchStyles = () =>
fetch(
"https://gist.githubusercontent.com/bionicvapourboy/61d3d7a8546cb42e0e3194eb9505f48a/raw/5432218dd83320d53d1cbc2f230b81c765183585/style.css"
).then(response => response.text());
class App extends Component {
state = {
style: ""
};
componentDidMount() {
fetchStyles().then(data => this.setState({ style: data }));
}
Wrapper = () => Styled.div`
${this.state.style}
`;
render() {
const Wrapper = this.Wrapper();
return (
<div className="App">
<Wrapper>
<h1>Styled</h1>
</Wrapper>
<h1>Not Styled</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
https://codesandbox.io/s/yw7xmx6x3x
You can try using this:
import React from 'react'
let cssLoaded = false;
export default class MyComponent extends React.Component {
render() {
if (cssLoaded === false) {
cssLoaded = true;
import('./MyComponentStyle.css');
}
// other stuff
}
}
And in your css file:
@import url('example.com/styles.css');
Source: React: Load component's CSS only when component is rendered
You don't even have to name it if you don't need to:
e.g.
import React from 'react';
import './App.css';
see a complete example here (Build a JSX Live Compiler as a React Component).
You need to use css-loader when creating bundle with webpack.
Install it:
npm install css-loader --save-dev
And add it to loaders in your webpack configs:
module.exports = {
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
// ...
]
}
};
After this, you will be able to include css files in js.
Make a new file and put this code in it.
export const style = { container : {
padding: 20,
border: '5px solid green',
borderRadius: 2 }
};
Now in your component file.
import * as styles from './style/location/filename'
Now you can use styles in your render function.
return (
<div style={styles.style.main}>
<h3 style={styles.style.header}>Vote for your favorite hack day idea</h3>
</div>
);
You can directly import your css file in js.
import './style/app.css';
app.css
.page {
background-color:#fafafa;
}
and you can use this class in React component like below.
<div className="page">
Hope it works!!!!