As we know, we are supposed to use lowercase and dash for css class name in raw html (e.g. <div class="lower-case-dash" />). What about in React JSX?
For html elements and other React components, what is the naming convention for css class name? camelcase or dash?
<div className="divClass">Something</div>
<div className="DivClass">Something</div>
<div className="div-class">Something</div>
<SomeComponent className="SomeComponent" />
<SomeComponent className="some-component" />
TLDR: PascalCase and Block__Element--Modifier
Check out the official doc of create-react-app. It provides a minimum example of creating a custom component. The js and css filenames as well as the className are all following PascalCase.
// Button.css
.Button {
padding: 20px;
}
// Button.js
import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles
class Button extends Component {
render() {
// You can use them as regular CSS styles
return <div className="Button" />;
}
}
Besides, the doc also provides an external link, which describes BEM naming conventions (link) for elements inside the component.
// MyComponent.js
require('./MyComponent.less');
import { Component } from 'react';
export default class MyComponent extends Component {
render() {
return (
<div className="MyComponent">
<div className="MyComponent__Icon">Icon</div>
...
</div>
);
}
}
// MyComponent.less
.MyComponent__Icon {
background-image: url('icon.svg');
background-position: 0 50%;
background-size: fit;
height: 50px;
}
Some of the naming conventions (Recommended) are:
Component Name
Component name should be in PascalCase.
For example, MyComponent, MyChildComponent etc.
Attributes
Attribute name's should be camelCase.
For example, className, onClick etc.
Inline styles
Inline styles should be camelCase.
For example, <div style={{color: 'blue', backgroundColor: 'black', border: '1px solid', borderRadius:'4px'}}>My Text</div> etc.
Variable Names
Variable names can be camelCase (Good practice), PascalCase (Avoidable), lowercase, can also contain number and special characters.
For example, state = {variable:true, Variable:true, variableName:true} etc.
Class Name
Class names can be anything camelCase, PascalCase, lowercase, can also contain number and special characters, because after all it is a string.
For example, className="myClass MyClass My_Class my-class" etc.
That totally depends on your (and your team's) preference. React (nor plain HTML) doesn't restrict you from using lower, dashed or camel-cased class names.
However, I would recommend that you choose an existing CSS convention like BEM. This will make sure that class names stay consistent throughout the process (if followed correctly).
We've chosen for a custom convention in our projects to match our components class names with the component name.
Example:
const NavBar = () => (
<header className="NavBar NavBar--fixed">
<div className="NavBar-brand"></div>
</header>
);
As you can see, this looks a lot like BEM, except for the pascal-cased block, single dash separator for elements and a double dash separator for block modifiers.
Related
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
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!!!
I have a component that has its own style, e.g.
.prompt { color: red; }
It's declared as so:
import cn from 'classnames';
import styles from './styles.css';
const MyComponent = ({className}) => {
return (
<div className={cn(styles.prompt, className)}>
test
</div>
);
}
In my specific use case, the stylesheet for the className being passed in is actually defined and added to the head BEFORE the stylesheet from the module, so the module's css always overrides the style of the className being passed in. Something like:
Notice the background: yellow from second class is being overridden by the background from the module's own class.
Other than using !important in the secondary class, how can I work around this?
Based on Mr. Lister's response, I re-evaluated my existing knowledge of specificity and came up with the following solution in the higher level css:
// in app.scss
.offline.prompt {
color: red;
}
// in app.tsx
const classes = cn(Styles.offline, Styles.prompt);
return <OfflineApp className={classes}>...</OfflineApp>;
Essentially, I just tag the module markup with another sibling class to increase specificity and target the necessary properties using that. WAY better than abusing !important.
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">
With the arrival of Material-UI#next comes the replacement of LESS-based styling with CSS-to-JS-based styling. However, the component demos on Material-UI's website appear to ignore the creation of props-based-styling. I'm trying to create divs containing various Material-UI components at specific absolute heights on my page, however, the requirement of the stylesheet being predefined outside of the class means that the properties within the stylesheet can't be based on props passed to the component. Am I missing something?
For example:
import React, {Component} from 'react';
import {withStyles, createStyleSheet} from 'material-ui/styles';
import Button from 'material-ui/Button';
const styleSheet = createStyleSheet({
container: {
position: "absolute",
top: /*How can this be dependent upon the props passed to the component?*/,
height: /*How can this be dependent upon the props passed to the component?*/,
}
});
class Foo extends Component {
render() {
let classes = this.props.classes;
return (
<div className={classes.container}>
<Button raised/>
</div>
);
}
}
export default withStyles(styleSheet)(Foo);
The example component displayed above can't have props-dependent styles, because props is not defined when the stylesheet is created. So how do I solve this problem? IS there a solution?
I would strongly advise you check out Styled Compoments. They make styling very simple and even allow you to pass third party components (in your case Material UI components). They also allow you to pass in props like the following:
const Stylesheet = styled.div`
color: ${props => props.primary ? 'white' :
`
<Stylesheet primary>My Div</Stylesheet>
Check out the docs for more details, that was a very simple example, but they are super easy to work with and you can accomplish exactly what you need with them.