ReactJS: Create isolated component with own css - javascript

I'm trying to develop a library of reactjs components in order to be reusable by different projects.
This components besides the functionality itself, must have a theme with different css styles.
I could write a css file, but then I must import the css in every project I will use any of that components. I need to set the style of this components inside itself, so when I import it in other project, I will looks exactly as I expect.
Is there any ReactJS library (or plugin perhaps?) to compile this styles inside the component or maybe apply a style on the componentDidMount?
EDIT
I forgot to add that I'm using MaterialUI. which is a framework that implements Material Design for React.
It provides different components which it own styles, and I can modify some of them, but not all.
Since Material UI create a big HTML I cannot add inline styles, that's why I need to add a selector to apply styles from React directly
Meterial UI provides something like that, so I guess is possible. This is how I configure in Material UI
const muiTheme = getMuiTheme({
palette: {
textColor: cyan500,
},
appBar: {
height: 50,
},
});
Sadly only some styles are supported by this, and not all I need

If you use webpack for your transpiling, you can create a separate stylesheet for the component and then import it.
Example:
import './componentStyle.css';
Then setup your component style in that CSS. The component would need both the jsx and css files each time you use them in different projects, but you can easily customize the css for each project if you need, and you can use css classes instead of inline styles.
Your webpack.config.js would need to have this:
module: {
loaders: [
{test: /\.css$/, loader: 'style-loader!css-loader'}
]
}

If you created application with npx create-react-app then
Import your styles from *.module.css file. Example: import styles from './component.module.css' with content .ssss { color: red }
Apply your style using {styles.ssss}. Example: <div className={styles.ssss}>

MaterialUI now includes CSS-in-JS docs functionality that will allow you to do just what you're asking.
you probably want to do something like what they suggest and make use of their HOC API:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '#material-ui/styles';
import Button from '#material-ui/core/Button';
const styles = {
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
};
function HigherOrderComponent(props) {
const { classes } = props;
return <Button className={classes.root}>Higher-order component</Button>;
}
HigherOrderComponent.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(HigherOrderComponent);

Related

Font-size with typescript customized font-awesome component [duplicate]

Solved - TLDR; Adding import '#fortawesome/fontawesome-svg-core/styles.css' to the _app.js / index.js file fixes the issue and FontAwesome works as intended. My issue was caused by npx-create-next-app including purgeCSS by default, which in turn stripped out the FontAwesome required styles.
I'm using FontAwesome in my Next app. I followed the React guide on the FA website and the icon SVG's are being output on the page. Problem is, none of the features work and they don't scale with font-size as they're meant to.
I don't want to hack it together by manually targeting the SVG's and adding size etc. as it's not ideal when it comes to responsiveness. i.e. it would be nice to have icons scale with accompanying text and the ability to add 'spinner', 'fixedWidth' etc.
Strangely, they have started working once or twice but then break again and I can't seem to reproduce.
// package.json
"dependencies": {
"#fortawesome/react-fontawesome": "^0.1.14",
"#fortawesome/fontawesome-svg-core": "^1.2.34",
"#fortawesome/pro-regular-svg-icons": "^5.15.2",
}
// _app.js
import { library } from '#fortawesome/fontawesome-svg-core'
import { faHeart } from '#fortawesome/pro-regular-svg-icons'
library.add( faHeart )
// header.js
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
export default function Header() {
return (
<header>
<FontAwesomeIcon icon={['far', 'heart']} spin />
</header>
)
}
// style.css
header {
font-size: 20px; (does nothing to the icon)
}
svg {
width: 20px; (works, but this shouldn't be required according to FA docs)
}
I've also tried individual use (importing icons into individual components, rather than utilising the library function) to the same effect. Like so:
// header.js
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faHeart } from '#fortawesome/pro-regular-svg-icons'
export default function Header() {
return (
<header>
<FontAwesomeIcon icon={faHeart} spin />
</header>
)
}
Fixed it. The issue was purgeCSS which was added to the project when using npx-create-next-app. purgeCSS was purging the required FontAwesome styles.
Explicitly importing the FontAwesome styles fixed the issue.
Specifically, I added import '#fortawesome/fontawesome-svg-core/styles.css' to _app.js.
According to the doc, The react-fontawesome component integrates well with Next.js but there is one caveat you need to solve. Since Next.js manages CSS differently
In your project entry, probably App.js
import { config } from '#fortawesome/fontawesome-svg-core'
import '#fortawesome/fontawesome-svg-core/styles.css'
config.autoAddCss = false
Next.js allows you to import CSS directly in .js files. It handles optimization and all the necessary Webpack configuration to make this work.
import '#fortawesome/fontawesome-svg-core/styles.css'
You change this configuration value to false so that the Font Awesome core SVG library will not try and insert elements into the of the page. Next.js blocks this from happening anyway so you might as well not even try.
config.autoAddCss = false
I use FontAwesomeIcon in my React apps like this and it works:
import { faHeart} from "#fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
in the code:
<FontAwesomeIcon className="icon" icon={faHeart} />
and in css:
.icon{
color: ; / if you want to change color
font-size: 36px;
}
Essentially, all you need to do is:
import the icon:
import { yourIcon} from "#fortawesome/free-solid-svg-icons";
and use it:
<FontAwesomeIcon icon={yourIcon} />
You can add a classname to the icon and use that class to style it.
<FontAwesomeIcon icon={yourIcon} className="styled-icon" />
Here is a good video on adding font awesome icons to next.js: https://youtu.be/kaA2aX4X3NU

Material UI v5 styles applied to class does'nt apply?

I am trying to style the MUI slider,so I decided to style it using the className prop. But the style applied to the main class does'nt get applied,while rest other styles like 'hover' state get applied. If I remove all the classes and just style it using SX prop,everything works fine. But I want to keep the styles seperate into an external css file.
Below is my code :
App.css
.container{
margin-left: 30%;
margin-top: 20%;
}
/* This does'nt get applied */
.slider {
color: #ff0000;
width: 300px;
}
.slider:hover {
color: #2e8b57;
}
.slider > .MuiSlider-thumb {
border-radius: 1px;
}
App.js
import "./App.css"
import * as React from 'react';
import Slider from '#mui/material/Slider';
export default function App() {
return (
<div className="container">
<Slider className="slider" defaultValue={30} />
</div>
);
}
The problem is with Material UI style injection order. The custom styles do apply, but Mui styles are injected before the custom style so they doesn't have effect in this case.
This guide explain how to change the injection order:
https://mui.com/guides/interoperability/#css-injection-order
I don't know if it is required, but I use css modules and material-ui. You can rename your css file to
App.module.css
then import like so
import styles from "./App.module.css"
you can then use it like
<Slider className={styles.slider} defaultValue={30} />
In Nextjs you can throw everything in styles.css to make it global, but I don't know if that is also for react as well.

styled components + reactstrap how to import bootstrap stylesheet after other stylesheets

I need to use bootstrap in a few of my projects and one problem I have is that for some reason the bootstrap stylesheet takes priority over the styled component styles.
import "bootstrap/dist/css/bootstrap.
const StyledButton = styled(Button)`
background: blue;
`;
intended result: use the background specifield in my component
actual result: StyledButton has the default bootstrap background
example here: https://codesandbox.io/s/p2wz01wnz7
I'm currently importing bootstrap in my index.js like this:
import "bootstrap/dist/css/bootstrap.css";
Is there a way I can force it to load last? I'm also using create-react-app just like in the codepen
I do not want to put
&&&{
}
around all of my styles.
You could place this import statement at the bottom of the header in your html file. If you have a css or scss import, just put it below that.

How to update style of a React element with className

So I'm using Ant Design UI library with my create react app which is making it difficult for me to edit the style of more complicated Ant Design components. Like the progress bar is by default blue:
I want to make it another color and when I look at HTML in the Chrome console I see:
The className for that element is ant-progress-bg. Is there any way I can write some code in my React component and update the style to be from style={width: "12.5%, height: 8} into style={color: 'red', width: "12.5%, height: 8}?
This is all the React code I need to write to generate the Progress bar using the ant design library:
import { Progress } from 'antd';
<Progress
percent={percentVotes}
showInfo={false}
status="active"
/>
I've also tried importing CSS and added an "ant-progress-bg" CSS class with the styling I want but it didn't do anything.
In my Matches.css file I have:
.ant-progress-bg {
color: red;
}
which I import into my Matches.js file with import './Matches.css';
Here is a demo https://codesandbox.io/s/k0m0nl1my3
If you want to change progress bar color for all places then override this class
.ant-progress-bg {
background-color: red !important;
}
And if you want to change color only for this specific progress bar, add some extra class like
.my-progress-bar .ant-progress-bg {
background-color: red !important;
}
If you are using less for your custom styles, it's even simpler
.my-progress-bar {
.ant-progress-bg {
background-color: red !important;
}
}
<Progress
percent={percentVotes}
showInfo={false}
status="active"
className="my-progress-bar"
/>

How can I use a .css stylesheet in React?

So I have a very large stylesheet and I'm attempting to use it in my React code. I know typically you would use this format for styling in React:
transparentBg: {
background: 'transparent'
},
WhiteText: {
color:'white'
},
However, my css stylesheet looks like this:
.transparentBg{
background: transparent;
}
.WhiteText{
color:white;
}
Is there anyway to convert my entire CSS stylesheet into that React-style format? Or a way for me to just use the original CSS stylesheet without converting it?
Your CSS is still just CSS and React still just renders HTML elements on the page.
This means that you can add your large CSS file into html file and just add CSS classes / ids etc. that you define there to the elements in React.
So if you have
.transparentBg{
background: transparent;
}
.WhiteText{
color:white;
}
Then in your React components you can use these classes:
var SomeComponent = function () {
return <div className="WhiteText">
Foo Bar Baz
</div>;
};

Categories