Nesting CSS selectors in material-ui? - reactjs

I can't figure out how to do the simplest thing in CSS using makeStyles from material-ui.
Imagine this super simple example:
<div classNames={clsx(wrapper, post.new && classes.new)}>
<p classNames={text}>Post</p>
<p> Something else </p>
</div>
The styles are really easy as well:
const useStyles = makeStyles({
wrapper: {
// styles
},
text: {
// styles
},
new: {
text: {
color: 'red', // this does not work, why? :[
}
}
});
You can probably guess by now what the problem here is. I want wrapper to have new class sometimes and when it happens text gets red. That's it. I have absolutely no clue how to do this.
I know there's '& .something' but this looks like a bad approach and I don't even know exact class name for text because classes are gibberish ( makeStyles-text-somerandomnumber). I don't want to add .new class to everything that needs extra styles, what if I there are multiple paragraphs that need different styles? Impossible to maintain. I guess I must be missing something, it's so trivial, yet, no idea how to do this!
Any help would be highly appreciated!

className={`wrapper ${this.state.something}`}
I see that your post is tagged with reactjs, if you are using React you can just dynamically apply the classes by whatever their state is.
Don't forget the backticks for template literals.

Related

How can i dynamically change images as Background in TailwindCSS?

I want to make a carousel, where the background is changing, i don't want to use the <img/> tag! I set the value as described in the documentation: https://tailwindcss.com/docs/background-image#arbitrary-values
My Code:
import React from 'react';
type CarouselProps = {
img: string;
};
const Carousel = ({ img }: CarouselProps) => {
return (
<div
className={`col-span-full bg-[url(${img})] bg-cover grid grid-cols-12 gap-6`}
> ...
</div>
);
};
When i set the String i pass to the Component hardcoded it works but when i use curly Braces and $ it doesn't. In addition i don't want to define my Background-Images in the tailwind.conf.js
The Error:
ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5]
.use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!
./node_modules/source-map-loader/dist/cjs.js!./src/index.css) 9:36-70
i don't want to define my Background-Images in the tailwind.conf.js
Well you have to. What you're trying to do isn't supported.
The way Tailwind scans your source code for classes is intentionally
very simple — we don’t actually parse or execute any of your code in
the language it’s written in, we just use regular expressions to
extract every string that could possibly be a class name.
so tailwind has no idea what your React code actually means. So it's simply not going to work.
Tailwind does not support dynamic class names:
Don't construct class names dynamically
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
you should customise your theme to include the image url:
You can add your own background images by editing the
theme.backgroundImage section of your tailwind.config.js file:
tailwind.config.js
module.exports = {
theme: {
extend: {
backgroundImage: {
'hero-pattern': "url('/img/hero-pattern.svg')",
'footer-texture': "url('/img/footer-texture.png')",
}
}
}
}
The solution is to use the style attribute. Thanks for helping :)
<div
className="col-span-full bg- bg-cover grid grid-cols-12 gap-6"
style={{
backgroundImage: `url(${img})`,
}}
>

Is there a way to easily add className to all tags in JSX?

I've been told that I shouldn't use HTML tags to style it in the CSS but rather use classes. Okay, not a problem I'll just add className to the tags. However there are quite a few of them in the code, so I was just wondering if there was a better way than just copy pasting the className into each tag or if there's a way to say for example all p tags should have class "text".
if all p tags should have a particular style then you should highly consider styling all the p tags directly via CSS
p {
font-size: 16px;
/* Your Styles here */
}
p.specific {
font-size: 24px;
/* Override styles for specific elements here */
}
Now answering the actual question. This can be done via JavaScript but once again I don't recommend this as this will have serious performance issues if there are a lot of nodes on the page.
document.getElementsByTagName("p").forEach(p => p.classList.add("text"));
Since you have tagged this as react, you can also extract the paragraph into its own component
const P = ({ children }) => {
return <p className="text">{children}</p>;
};
You can either add class to all elements like Mailk suggested.
document.querySelectorAll("p").forEach(p => p.classList.add("text"));
or you can simply find and replace all the p tags using the text editor.
find: <p
replace to: <p className="text"

React set dynamic style in a component

This has been asked several times but in my use case it's not working. I'm sure I'm missing something.
In a functional component I do:
const headerImg = {
backgroundImage: `http://localhost:1337${data.service.main_image.url}`
};
Then in a div I do the following:
<div className="bread-cumbs-area" style={headerImg}>
I'm attempting to use headerImg.backgroundImage as the background image but it's not displaying in my div. Any idea what I'm doing wrong?
Since you're setting the background image in CSS, you need to use the url() CSS function:
const headerImg = {
backgroundImage: `url('http://localhost:1337${data.service.main_image.url}')`
};

How to get CSS Modules to work with Reactstrap cssModule propType?

I noticed most form elements in the Reactstrap documentation have a PropType of a cssModule. I would assume that means I could override the default Reactstrap styles and do something like this:
Formtext.module.css
.formtext {
background-color: blue;
border: 2px solid black;
margin: 10px;
}
SimpleForm.jsx
import styles from "./Formtext.module.css";
...
<FormText cssModule={styles.formtext}>
This is some placeholder help text...
</FormText>
```
However, this doesn't seem to work. Checking my react dev tools the cssModule prop evaluates to undefined.
I'm using Using Reactstrap 5.0 and create-react-app 1.1.5
Is there something I'm unaware of that I need to do?
Do I need to eject to be able to use css-modules?
Can someone point me to an example of how to use the Reactstrap's cssModule prop correctly?
For reference here is the proptypes definition from Reactstrap docs
FormText.propTypes = {
children: PropTypes.node,
inline: PropTypes.bool,
tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), // default: 'small'
color: PropTypes.string, // default: 'muted'
className: PropTypes.string,
cssModule: PropTypes.object,
};
On cssModule
It looks like cssModules doesn't behave quite like you would think; the prop doesn't take a single, overriding class - it takes a rejected class and a replacement class.
Reactstrap uses mapToCssModules to get this done. See its documentation here. Take note of the usage example:
<Example tag="div" cssModule={{ 'w-100': 'w-75' }} />
So your case would look something like this:
<FormText cssModule={{ 'form-text' : styles.formtext }} />
This will completely surpress the 'form-text' class though (which in your case, only contributes display: block. If you'd like to override more selectively, see below.
Try this instead
In the FormText source code, it looks like you may be able to do your overrides in a different way:
If you want to omit the form-text class altogether, include inline as a prop,
If you want to omit any color-related bootstrap classes, set 'color' to false (or something falsy),
set the className prop to your CSS Module object (styles.formtext).
<FormText className={styles.formText} color='' inline>
Test formtext
</FormText>
The most important part here is actually the className prop. You can also further override styling by including a tag prop (again, check the FormText docs).
Hope this was helpful! Happy holidays! 🦃🎅
I did not really get the accepted answer, but I had the same problem recently and in my opinion, cssModule behaves exactly as one would expect.
You just pass an imported module object and then specify classes they will be referenced towards the module.
Here is my example (from create-react-app) how I did fix Navbar to get it's bootstrap styles from my bootstrap module (as I don't import bootstrap globally):
import cx from 'classnames';
import bootstrap from 'bootstrap/dist/css/bootstrap.css';
import navbar from './navbar.css';
let styles = Object.assign({}, bootstrap, navbar);
public render() {
return (<Navbar cssModule={styles} className={cx(styles.navbarExpandSm, styles.navbarToggleableSm, styles.borderBottom, styles.boxShadow, styles.mb3)} light>[your menu here]</Navbar>);
}
This simply says the control to take the styles module and reference all the class names passed in classNames towards it. If you take a look at the mapToCssModules method, it is exactly what it does.
https://github.com/reactstrap/reactstrap/blob/d3cd4ea79dcaf478af5984f760ff1290406f62a5/src/utils.js#L53
In my case, it allows the control to pick up the original bootstrap styles and I can override what I need in my own module.

how to use common less variable with styled component?

Say I have a styled component, in index.jsx
import './index.less';
class Input extends React.Component {
...
}
and my index.less files looks:
.input{
color: #whiteColor;
}
This index.less has to work with the mixin.less that imported in the root project.
So my question is, even though I imported the mixin.less, it prompts variable #whiteColor not found. Any idea to solve this?
I have felt the same pain, why isn't my styled component resolving less variables?
The syntax is simple JavaScript, just do:
.input{
color: ${props => props.whiteColor};
// or
color: ${props => props.theme.whiteColor};
}
But, at my company, we had thousands of less components, and we really thought that the less syntax was cleaner and definitely faster to write. We developed Styless.
It is a babel plugin that parses less and generates javascript code. Add it to your .babelrc file.
{
"plugins": ["babel-plugin-styless"]
}
Then, we can do!!
const Input = styled.input`
#highlight: blue; // can be overwritten by theme or props
background: darken(#highlight, 5%); // make green darken by 5%
`;
Check here to see how to use the theme provider and load variable from your index.less!
You can try import the mixin.less in index.less
I have been trying the same than you.
But then I thought.. it is that what I really want? Because styled-components propose a different approach to having a modular structure for your styles.
https://www.styled-components.com/docs/advanced Check theming, is amazing powerful.
Because in styled components you define the variables with javascript.
And if you want color manipulation like less, sass, you can check https://github.com/erikras/styled-components-theme
Its like forgetting about less, and sass and moving it to a new style modules.
Still, if you want to keep your defined style classes, you can do that:
class MyComponent extends React.Component {
render() {
// Attach the passed-in className to the DOM node
return <div className={`some-global-class ${this.props.className}`} />;
}
}
Check the existing CSS usage from docs:
https://www.styled-components.com/docs/advanced#existing-css

Resources