I am using prime-react to style my React page. But I want a more compact website with very few padding and minimum styling. For this purpose, I want to override a few CSS properties for the prime-react components.
For eg, I am trying to reduce the padding for the MenuBar -
HomePage.js
import {React, Component } from 'react';
import { Menubar } from 'primereact/menubar';
import 'primereact/resources/themes/saga-blue/theme.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import styled from "styled-components";
export default class HomeMenuBar extends Component {
// menu code ...
render() {
return (
<div>
<div className="card">
<Menubar model={this.items} className={this.props.className} />
</div>
</div>
);
}
}
const ComponentView = styled(HomeMenuBar)`
.p-menubar .p-menubar-root-list > .p-menuitem > .p-menuitem-link {
padding: 0.1rem 1rem !important;
}
`;
The above code makes no difference to the original styling.
I am trying to make use of this component.
However, particularly using these styled-components I don't like it. I am new to react and would like to know if there are better alternatives like, storing the CSS properties in another file and then importing it in the required file. I tried this part but it also didn't work out.
I work with react over a year and have seen lot of different ways to customise components and so far, I think that styled-components is the most convenient way to customize components if you cook them right.
I love to put all customized components with styled to a separate file near the index.js called styled.js of Component.js and Componnet.styled.js (in the separate folder of course MyComponent/index.js);
In styled.js you export all components like this:
export const Container = styled.div`
.p-menubar .p-menubar-root-list > .p-menuitem > .p-menuitem-link {
padding: 0.1rem 1rem !important;
}
`
In index.js file you inport them like this:
import {Container} from './styled'
// or import * as Styled from './styled' (if you have a lot of customized components);
export default class HomeMenuBar extends Component {
// menu code ...
render() {
return (
<Container>
<div className="card">
<Menubar model={this.items} className={this.props.className} />
</div>
</Container>
);
}
}
If you want to try something more like classic css try to look at css-modules.
This article can help https://www.triplet.fi/blog/practical-guide-to-react-and-css-modules/
You can also try patch-styles, a more declarative way to apply CSS/SCSS modules to your code. Also, check out the StackBlitz example.
Related
In one React app with React Router, for each route component, I would like to have one local scss file only apply to this file.
For below example, about.js imported about.scss, what I want to have is: about.scss override the global style in app.scss only in about.js. However, it overrode everything in the app
app.js - imported app.scss which I prefer as a global style
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import "./app.scss"; // global scss
import About from "./about";
export default function App() {
return (
<>
<h1>question about scss in react route</h1>
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</div>
</Router>
</>
);
}
function Home() {
return (
<div>
<h3 className={"myMargin"}>home</h3>
</div>
);
}
app.scss (the global style)
h3.myMargin {
margin: 10px
}
about.js
import React from "react";
import "./about.scss";
export default function About() {
return (
<div>
<h3 className={"myMargin"}>About</h3>
</div>
);
}
about.scss (I want to be a local style, however, it applied to everywhere in the app)
h3.myMargin {
margin: 100px
}
Any suggestion how to structure my style code?
The beauty (and caveat) of CSS is in the first C of its acronym —which stands for cascading— meaning there is a cascade of (fairly predictable) rules to follow.
In this case about.scss being imported later, will override your h3 from app no matter what.
1) Use a container:
import React from "react";
import "./about.scss";
export default function About() {
return (
<div className='about-page'>
<h3 className="myMargin">About</h3> // note: no need for {"myMargin"}
</div>
);
}
// about.scss
.about-page {
h3.myMargin {
margin: 10px
}
}
2) Using CSS Modules:
Another one is to use CSS Modules, enabled by default if you use a fairly recent version of create-react-app:
import React from "react";
import styles from "./About.module.scss";
export default function About() {
return (
<div>
<h3 className={styles.myMargin}>About</h3>
</div>
);
}
// About.module.scss
.myMargin {
margin: 10px
}
This will generate a unique className, so your processed code will look something like this:
<div>
<h3 class='About_myMargin_mVxOd>About</h3>
</div>
The random hash (mVxOd as an example) will allow your styles to not overwrite each other.
There are pros and cons of both methods, the biggest problem when using regular CSS/SCSS imports is that you are at the mercy of the rules of CSS: if you accidentally create a global class .error then the rules will cascade to any component and its hard to keep track. Importing Bootstrap for example, will overwrite a whole lot of CSS names that you have no idea about (until you realize your CSS is off).
Another problem is that, if a said route doesn't import a CSS file, but later on following a different path of routes does import the file, you could end up with different styling. This has happened to us a few times, so it's a must to be extra careful especially in bigger teams.
CSS Modules has a few big drawbacks, first one being that you cannot directly override a style from another CSS file just by overriding its CSS class (because of said hash). Second, you cannot access nested CSS selectors allowed by SASS.
I personally have used both for production and personal projects and both are equally great -- when used carefully.
There is a third popular option called Styled Components. It's personally not my preferred and I haven't used it much, but you can learn more abouut it on its official page. It looks like this:
const Title = styled.h3`
margin: 10px;
`
render() {
return <Title>About</Title> // creates an h3 tag
}
One last one, being CSS in JS which I haven't used enough either.
I wrote a Logout button component in my React app for which I wish to locate at the top right corner of the screen.
render() {
<LogoutButtonComponent height: , backgroudColor: />
}
It wouldn't let me assign any values for height and etc.
This is the Logout component:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class LogOutButton extends Component {
static contextTypes = {
store: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onLogout();
};
render() {
return <button type="button" onClick={this.handleClick}>Logout</button>;
}
}
Should I locate it by < col /> ?
To add inline styles, you should defined a style object as prop, and pass it values, like doniyor2109 mentioned. There are a few caveats to using this, however.
style={{ height: 100, height: '100px', height: '100%', minHeight: '100px'}}.
Not every value should be passed as integer, some need to be passed as a string
Not every css attribute gets passed as you would expect them to, the css min-height actually gets passed as minHeight, so replace all hyphens with lower camel case style
Inline styles get insanely difficult to manage. I suggest you at the very least create an object outside the component, and pass it in like:
const DivStyle = { minHeight: '100px' }
and then:
<LogoutButtonComponent style={DivStyle} />
You can prefix that DivStyle with an export if you want to import {DivStyle} from './somefile' in other places
I suggest you check out a library like styled-components as it makes styling much easier!
I suggest you check out this article which outlines your options
You don't really add styles to your component like that. It's better to add those styles in the source for the actual component. So how exactly do you want it displayed? I will provide a template kind of and you can change it to what you want.
Go to your source for your Logout Button Component. In the return of your render method try adding a div call it container. Then add styling in a css file to that div or if you are using react-bootstrap or reactstrap or #material/ui/core you can adjust the style according to their documentation.
You can add your css for the className .container to make it appear the way you would like.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class LogOutButton extends Component {
static contextTypes = {
store: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onLogout();
};
render() {
return (
<div className="container">
{* notice the className here *}
<button type="button" onClick={this.handleClick}>Logout</button>
</div>
)
}
}
Hope this helps.
In the create react app documentation it says the App.css is imported in the App.js. Is there also a way to load the compiled css-file from a component?
// MyViewComponent
import styles from '../../App.css';
You can just import the css file like the below in your component
import './header.css';
Imagine your header.css file looks like
.header {
background-color: rgb(49, 118, 197);
height:100px;
border:10px solid red;
}
To use the style, you can use the class like ,
<div className="header">Hello World</div>
Hope this helps :)
For css files you can just import them like
import "../../App.css"
which will import all of the selectors & CSS rules within that file.
if you're trying to style individual elements within your component with something like:
<div style={myStyles.wrapper} />
then you'll need to export a JS object from a file
Ex:
export default {
wrapper: {
background: "red"
}
}
then you can import it and use it
import myStyles from "../myStyles.js"
<div style={myStyles.wrapper} />
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.