I am trying to import styles from a .css file into a react js file using "import '../css/banner.css', with css-loader and style-loader installed and enabled. It should be the most direct and simplest method to import css in react, but the styles just won't apply.
I am trying to achieve this without using other libraries like styled-components or jss.
banners.css:
.headerItem{
width: 20vw;
float: left;
background-color: cadetblue;
margin: auto;
padding: 3em;
text-align: center;
}
Header.js
import React ...
import '../css/banners.css'
class Header extends React.Component{
constructor(){
}
render(){
return (
<div className={"header"}>
<HeaderItem/> //shown as an example, has className of "headerItem"
</div>
)
}
}
The problem is not relevant to wrapping curly brackets around the class name or not. I found out that in my webpack.config.js I had set the modules option in "css-loader" to be true, which led to the css-loader looking for modules.css files instead of .css files. Changing the modules option to false solved my problem. (If you are using css modules then remember to set the flag to the correct value!)
As a matter of fact, arguments to be passed onto a React component should always be wrapped in curly brackets, and even if you don't the compiler will automatically add them for you since every argument is treated as an object, which would then be collected and passed as props down to the Child Component.
Apologies for raising such a trivial and wrongly-focused question.
Try this one. Dont use {} in className
<div className="headerItem">
<SomeChild/> //shown as an example
</div>
The best and simplest way to include CS into your react project is;
rename your file to [FileName].module.css
import it into your project using import importedStyles from './[FileName].module.css
use it by calling the imported name . the css style you want to use. eg importedStyles.bodyStyle
rename bannerss.css to banners.module.css:
.headerItem{
width: 20vw;
float: left;
background-color: cadetblue;
margin: auto;
padding: 3em;
text-align: center;
}
Header.js
Call the css file into your project and use;
import React ...
import bannerStyles '../css/banners.module.css'
class Header extends React.Component{
constructor(){
}
render(){
return (
<div className={"bannerStyles.header"}>
<HeaderItem/> //shown as an example, has className of "headerItem"
</div>
)
}
}
This should work fine and its easy.
Reference: https://www.w3schools.com/react/react_css.asp
Let me know if this works!
Dont use curly braces , or best you can use styled components to give css property
Related
I have some issue using scss directly in material ui, because not all styles are applied. Tried to use makeStyle, but because I use class component, it gives warning about invalid hook call.
The style :
.table-header {
background-color: #005CAA; //only this style works
color: white;
font-weight: bold;
text-align: center;
}
I call in in TableCell component from Material UI
<TableCell className="table-header">Invoice Number</TableCell>
For the scss file, I import it in parent component App.tsx, or I need to import the file directly in the Table component? Thx
I follow the makeStyles approach as it's recommended way of overriding the material-ui styles, else you'd have to use !important in your css/scss files to override the material-ui styles.
https://mui.com/styles/basics/
// component file
import React from 'react';
import { TextLineStyles } from './styles';
export default function TextLine({ text }) {
const classes = TextLineStyles()
return <div className={classes.root}>
<div data-title="line" >
<div data-title="text">
{text}
</div>
</div>
</div>
}
// style.js
import { makeStyles } from "#material-ui/core/styles";
export const TextLineStyles = makeStyles(theme => ({
root: {
'& [data-title="line"]': {
borderTop: `1px solid lightgray`,
'& [data-title="text"]': {
color: 'red' // scss like nesting
}
}
}
}));
If you want to use CSS/SCSS class in MUI component, you should import the file directly in the Table component. But, it's not good to use SCSS with MUI component, you should use makeStyles or withStyles to style the MUI component.
I am not sure if it is the best practice, in fact thats why I ended up in this post.
Here it explain how to use scss with material-ui: https://www.markmakesstuff.com/posts/mui-css-modules
"Just install node-sass"
"if you're working with an app you initialized with a script like create-react-app, you are in luck. No webpack edits necessary. Just give your module a name that ends with ".module.scss""
OTHERWISE
2') You need to "make some minor edits to your webpack config"
"You can then import your module with a name then use that to refer to your classes when writing your fancy JSX"
I installed 'react app 2' as well as node-sass. It's working fine with SCSS. But I just want to know how can I create component specific SCSS like Angular (that will never be a conflict with other components SCSS)
Angular automatically add an attribute for ViewEncapsulation see below example
In angular, there is an option for
encapsulation: ViewEncapsulation.None (Use to disable CSS Encapsulation for this component)
enter link description here
I know the question is old, but it has no answer, thus I want to share this article. Alsomst does the trick, with the exception that it seems to does not have support for something like ::ng-deep
React doesn't have native component styles like Angular does because it aims to keep away from any functionality that could easily be handled by third-party packages. So you have two pretty simple options:
Use styled-components to create component-specific styles. This is a pretty straightforward package that allows you to define styles for each element within a component and you can even pass variables into the styles. It generates internal CSS (kept in <style> tags in the document head) which will take precedence over external styles by default. Example:
// MainComponent.jsx
import React from 'react';
import styled from 'styled-components';
const Title = styled.h1`
color: red
`
const MainComponent = (props) => <Title>Hello World</Title>
In each of your components, add a class or ID to the root element so that you can simply add that selector to the beginning of your SCSS to only style that specific component. Example:
// MainComponent.jsx
import React from 'react';
const MainComponent = (props) => (
<div className="main-component">
<h1>Hello World</h1>
</div>
)
// MainComponent.scss
.main-component {
h1 {
color: red;
}
}
Now only h1 elements in your MainComponent will be red.
//JS
import React from "react";
import "./yourComponentName.scss";
export default props => {
const { className, children, ...restOperator } = props;
return (
<a className={`yourComponentName ${className}` } {...restOperator}>
{children}
</a>
);
}
//yourComponentName.scss
.yourComponentName{
position:relative;
background:red;
/* your property and value use nesting*/
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
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!!!
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">
I have the following .scss file
div.topMenuIndex {
ul {
&:before {
content: "☰";
padding: .15em .25em;
text-align: center;
background: #ea764b;
color: #f8d4c6;
}
&.LoginStatus{
background: azure;
}
}
Now I import this into my react component
import styles from "./TopMenuIndex.scss";
When defining the component how do I refer to div.topMenuIndex.LoginStatus in my div element
Hello jim
You can use className=""
So in your case, put <div className="topMenuIndex LoginStatus"></div>
The styles object will have all your classnames as key and corresponding hash as the value.
So your need to use styles[<classname>]
Example
<div className={`${styles[topMenuIndex]} ${styles[LoginStatus]}`} />
Hope this helps!
I highly recommend using react-css-modules if you can. You will just need to wrap your component with a decorator, but using your styles will be so much easier.
Here's how
npm i -S react-css-modules
In YourComponent.js
import CSSModules from 'react-css-modules'
import styles from "./TopMenuIndex.scss";
Then somewhere down in your component you will just use them as names, but using styleName instead of className
<div styleName="topMenuIndex LoginStatus">test</div>
and you export your component like this at the end
export default CSSModules(YourComponent, styles, { allowMultiple: true });