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

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"

Related

How to pass custom class name on react and use scss?

I am trying to create a react component that has the class name as props being passed,
I have managed sending the props part successfully, however when I try to set the scss for the updated class name, I could not find a way to fix that, all of your input is appreciated.
Code of the component
Code of injecting the custom style class
Styles of the Variation
Output
Output of the Variation Class
Output of the Stylesheet
not sure what I am missing to connect all of them.
Thanks in advance.
As mentioned by Phil, your SCSS should be using &.secondary as the selector.
As for the difference in your scss class IDs and them not matching when you pass ${variant} to the className, your issue is that you are passing a raw string as the variant to the className and are using CSS modules for your SCSS (this is what handles namespacing them/adding the unique characters). To fix this, you need to use the imported style rather than a raw string for the className.
The way I usually address this is with an enum as the prop for different variants, or if there are only two a boolean, and then apply the imported style accordingly. A quick example of this, using your code would be:
const SectionTitle: FC<SectionTitleProps> = ({ title, isSecondary = false }) => (
<h3
className={`${styles.SectionTitle}${isSecondary ? styles.secondary : ''}`}
...
>
...
</h3>
);
I also find the classnames library helpful for this. It allows you to achieve the above with something I find a bit more readable, such as:
<h3
className={classNames(styles.SectionTitle, { [styles.secondary]: isSecondary } )}
...
>
...
</h3>
EDIT: Also including an example using classnames with an enum for different variants:
enum TitleVarient {
Default,
Secondary,
Accent,
}
const SectionTitle: FC<SectionTitleProps> = ({
title,
variant = TitleVarient.Default,
}) => (
<h3
className={classNames(styles.SectionTitle, {
[styles.secondary]: variant === TitleVarient.Secondary,
[styles.accent]: variant === TitleVarient.Accent,
})}
...
>
...
</h3>
);

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})`,
}}
>

Nesting CSS selectors in material-ui?

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.

what does this syntax in styled-components actually mean?

I've just started using styled-components and saw that they call what i presume is a function like so:
import styled from "styled-components"
const Button = sytled.button` <--- this
// css goes here
`
I've never seem that syntax before and wanted to know if someone could point me to some docs about what it actually is.
It's called tagged template literals. The "tag" is the function before the template literal, which is called with its parameters being the template and template's variables. The parameters are as follow:
An array with all the string parts between the ${variables}.
First ${variable} of the template.
Second ${variable} of the template.
etc...
For example, I have written a function named tag that does the same as the function template literals use to process when you don't specify any tag function (a.k.a its default function):
function tag(stringParts, ...values){
return stringParts.reduce((accum, part, index) => accum + values[index-1] + part);
}
Calling it this way
tag`Hello, ${name}! I found ${count} results.`
yields the same result as
`Hello, ${name}! I found ${count} results.`
and the params fed to the tag function are ['Hello, ', '! I found ', ' results.'], name and count.
That's how you set the CSS rules for the <button> element.
So then you can use it as such:
<Button>Hello world</Button>
and all the styles you wrote above would get applied to all <Button> elements
Styled-components is a library used for styling react components.
import styled from "styled-components"
const Button = sytled.button` <--- this
// css goes here
`;
`` <-- these are template literals which was introduced in ES6.
styled is an object here and when you say styled.button it means that we are styling html tags. So you can style a div, container, h1 etc. You want to use standard css to style these html tags and styled-components create a random classname for the same.
let's say you want to style a div. You name it a Wrapper. The naming covention is first letter always capital.
const Wrapper = styled.div`
background: #c0c0aa; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #1cefff, #c0c0aa); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #1cefff, #c0c0aa); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
height: 100%;
width: 100%;
`;
now you can wrap your content in render () of react.
<Wrapper>
//Your code in render of react class goes here
//thus instead of <div className = 'Wrapper'>
//you use the above code
//styled-components automatically generates random classnames solving major problems
</ Wrapper>
for more information see Max Stoiber's keynote at React Amsterdam.
https://www.styled-components.com/docs/basics#motivation

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