How to apply css to components in Next JS - css

I have an app in next js that is also using chakra UI. I am attempting to add a footer to the app, but am unable to force the components under the navbar to take up the remaining height of the screen.
I think my issue is that I am not correctly passing CSS styling down to the components.
_app.tsx
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return (
<ChakraProvider theme={theme}>
<Navbar></Navbar>
<Component id='component-container' {...pageProps} />
)
}
export default MyApp
styles/globals.css
#component-container {
height: 100%
}
Even when I set the #component-container to something like color: white I do not see this CSS applied to the child components. I don't think I am correctly passing the CSS down to the components.
How do I correctly apply CSS to all components in next js?

You need to pass that ID to an HTML element inside that component...
Right now you are only passing that ID as a props to that component and probably none of the elements inside it have that ID(as I don't know what the code is for your component).
Go inside that component and either give that ID to which element you want(Probably the first DIV element) or pass it as a props to that element

Related

How to use components in different ways (React)

I want to use simple components in different way and different ui rendering
For example a dropdown rendering a list may have several ui according to the page or context (=> padding, margins, font size and other css properties might change)
should I:
implement it by overwriting in the parent component (target css properties of the child component and apply them my css needs - at cost that if change happens in the child component like change in classname or what might break the parent design)
Pass flags to the component to handle those design and at cost that each component handle the design of each parent
There are different approaches to this and everybody has his own preferences.
I usually solve this by supporting the className property. The class is accepted as a prop and applied to the root. So it is easy to change things like outer margins or the background-color. I usually discourage modifications of deeply nested elements.
Example:
import classnames from 'clsx';
import style from './button.module.scss';
export const Button = ({ content, onClick, className }) => {
return (
<div
className={classnames(style.buttonRoot, className)}
onClick={onClick}>
{content}
</div>
);
};
and if I want to modify it anywhere I can do it thus:
import { Button } from './Button';
import style from './productView.module.scss';
// ...
<Button content={'Show products'} className={style.showProdButton} onClick={showProd} />
and
.show-prod-button {
background-color: #562873;
margin-left: 32px;
}

How to style Antd component

I am working on Switch component with antd library. I would like to change background of switch, so I have following code:
import styled from 'styled-components';
import { Switch as SwitchhAnt } from 'antd';
export const Button = styled(SwitchhAnt)`
.ant-switch-checked {
background-color: red;
}
`
But switch background does not change at all. I know I can wrap this in some container and it will works but why something like that does not works?
As per how styled components work under the hood,
It creates a unique class name by hashing styles into a seemingly-random string, like dKamQW or iDwMsQ.
Then inject a new CSS class into the page, using that hashed string as its name, and containing all of the CSS declarations from the styles string. You can see that when you inspect switch that different style classes have been applied.
Normal antd Switch
Styled antd Switch
So here you don't need to add the class name used by antd. Just only need to add CSS properties that need to have like below.
export const Button = styled(SwitchAnt)`
background-color: red;
// ....... other styles
`
You can check example codesandbox in here.
You can also refer demystifying-styled-components and how-styled-components-works for more details about what styled components do under the hood.

Apply outer style to Gatsby StaticImage using twin.macro

I am using StaticImage from gatsby-plugin-image together with twin.macro for CSS styling and followed this guide: https://github.com/ben-rogerson/twin.examples/tree/master/gatsby-styled-components#getting-started
...
import tw, { css, styled, theme } from 'twin.macro'
import { StaticImage } from 'gatsby-plugin-image'
...
<StaticImage
imgStyle={tw`rounded-lg shadow-2xl`}
style={tw`p-4`}
src="../images/image.jpeg"
width={300}
quality={95}
formats={['AUTO', 'WEBP', 'AVIF']}
alt="Description"
/>
Styling the inner img element with 'imgStyle' works with twin.macro. However applying the same technique for the style property of StaticImage leads to the following error:
Styles shouldn’t be added within a style={...} prop
How can I apply twin.macro to the style property of StaticImage?
According to the Gatsby Image plugin docs:
The images are loaded and processed at build time, so there are
restrictions on how you pass props to the component. The values need
to be statically-analyzed at build time, which means you can’t pass
them as props from outside the component, or use the results of
function calls, for example. You can either use static values, or
variables within the component’s local scope.
So the code should look like this:
// Also OK
// A variable in the same file is fine.
const width = 300;
const height = 300;
const imgStyle= tw`rounded-lg shadow-2xl`;
export function Dino() {
// This works because the value can be statically-analyzed
const height = (width * 16) / 9
return <StaticImage
src="../images/image.jpeg"
width={width}
height={height}
style={imgStyle}
/>
}

How to add background image on a material ui Dialog component

I'm using material-ui version 3.9.3 in my React application. I want to add a background image on a dialog. I'm using the Dialog component for it but I'm unable to add a background image on the whole dialog.
For example:
<Dialog
fullScreen={fullScreen}
open={this.props.open}
onClose={this.handleClose}
aria-labelledby='responsive-dialog-title'
>
<DialogTitle
id='customized-dialog-title'
onClose={this.handleClose}
noCloseButtonNeeded={noCloseButtonNeeded}
>
{/* some jsx */}
</DialogTitle>
<DialogContent>
{children}
</DialogContent>
</Dialog>
I have tried to add an image using classes and custom CSS but I'm unable to do it.
Can anyone help me out to add it? Thanks in advance :)
First, you can define the background image in a styles object that can be used with the withStyles higher-order component to apply it to the dialog:
const styles = {
dialog: {
backgroundImage: "url(https://i.imgur.com/HeGEEbu.jpg)"
}
};
When you pass this object to the withStyles HOC, it will supply your component with a classes prop containing properties with the same names as the properties on styles that you've defined.
Next, you can apply this class to the Dialog by taking advantage of the classes prop (the specific overrides made available for the Dialog component are detailed here):
<Dialog ... classes={{paper: classes.dialog}}>
{/* ... */}
</Dialog>
This is telling material-ui to merge the styles you have defined in styles.dialog with the default styles on the Paper element that is used with the Dialog.
You'll need to make sure that you're wrapping your component in the withStyles HoC. If you have a class component, it will look something like this:
export default withStyles(styles)(DialogWithBackgroundImage);
For functional components, it would look something like:
export default withStyles(styles)(({open, children, classes}) => (<Dialog ...></Dialog>))
Here's a working example that ties everything together: https://codesandbox.io/embed/q3zy4r2np4

Applying CSS stylesheet only to active component

I'm working on a ReactJS app that has a header at the top, a menu on the left, and the "frame" in the middle is where routes and their corresponding components are loaded. I want to be able to apply a CSS stylesheet to specific components only when they are loaded. I also don't want them applied all the time or to the top header or left menu.
My expectation was that adding import 'custom.css'; to a specific component would only apply the stylesheet's styles to that component and it's children when the route is active. Instead, it applies it to the entire page even when the route/component are not loaded.
I understand that an alternative approach is styled components, but, for my use-case, a design company is supplying a stylesheet (which should remain unchanged) that we need to consume only for the sub-module I'm working on and I don't want its styles to affect the rest of the app.
How can I have a stylesheet only applied to my active route/component?
Use simple CSS technique. Suppose you have two components with different css files (say about.css and contact.css). Now consider your both CSS file have one common class with different style properties, like:
about.css
.container{
max-width: 400px;
}
contact.css
.container{
max-width: 500px;
}
Yes in ReactJS both the CSS files will load at the same time and will override any one of the style. so to solve this problem add class to differentiate this styles, like:
about.css
.about-component.container{
max-width: 400px;
}
contact.css
.contact-component.container{
max-width: 500px;
}
If you want apply only when the component is mounted, you can use the lifecycle.
The follow example is based in the idea you are using sass, React, sass-node and have the loaders into webpack.
<pre>
import React from 'react';
import './styles.scss';
class MyComponent {
constructor(props) {
super(props);
this.state = { className: '' }
}
componentDidMount() {
this.setState({
className: 'myOwnClass'
});
}
render(){
return (
<div className={this.state.className}>This is a example</div>
);
}
}
export default myComponent;
</pre>
To be able to only call that specific CSS when you need it you can use CSS Modules. You may need to update your version of react.
When saving your CSS file save it with a ".module.css" eg. "styles.module.css". The CSS in these files can only be used and accessed by hte components where are they are imported. As stated in a tutorial from W3Schools.
Let's say this is your CSS code in styles.module.css:
.container {
color: white;
}
.cont-child {
background-color: red;
}
Then in your JS file you can import the CSS file like this if the JS and CSS files are in the same directory. Make sure you point to the correct path.
import styles from './styles.module.css'
Then in your HTML section you can use it like this:
class Home extends React.Component {
render() {
return(
<main className={ styles.container } >
<div className={ styles["cont-child"]} >
Some div text about something...
</div>
</main>
);
}
}
I currently use both ways to access the selectors, since the styles variable acts like an object. I placed both of them here because the second option is capable of fetching selectors named like "btn-active". Which comes in handy in some situations. Camelcasing is considered cleaner though.
Please note: I originally posted this answer as a reply to a similar question here React CSS - how to apply CSS to specific pages only
I want to be able to apply a CSS stylesheet to specific components
only when they are loaded.
Why not apply the styles inline via React.js?
Step 1. Create the style object for the component:
var componentOneStyle = {
color: 'white',
backgroundColor: 'red'
};
Step 2. Populate the component's style attribute with the style object:
ReactDOM.render(<div style={componentOneStyle}>This is Component One</div>, mountNode);

Resources