Override Mantine styles to only one element - javascript

In my React project, I am using Mantine's library accordion in two different components: Search.jsx and Profile.jsx.
The point is I need to accurately customize its styles only in Profile so I inspected the element and discovered that the default Mantine's class is named mantine-bgzycs. I applied styles to that class in Profile.css and it worked as I wanted.
The problem is that affects to Search's accordion element too.
When I inspect I can see also a Mantine's default ID but it changes dinamically.
I tried to envolve the elemen with a div and apply styles but most of them are overwritten by Mantine.
QUESTIONS:
Is there a way to apply styles only to one element of the same class?
Is there a way to restrict styles between React components?
Is there a way to access to Mantine's source and edit accurately an element styles?
Thanks very much in advance!

There is more than one way to achieve what you're after. My preferred approach is documented in the Styles API panel of the Accordion documentation and in the theming documentation under create styles and Styles API
Here is an example:
import { createStyles, Accordion } from '#mantine/core';
// define custom classes - includes access to theme object
const useStyles = createStyles((theme) => ({
item: {
backgroundColor: "red",
},
}));
function Demo() {
const { classes } = useStyles();
return (
<Accordion
// apply custom classes to target Styles API properties
classNames={{ item: classes.item }}>
<Accordion.Item label="Customization">
Blah, blah, blah
</Accordion.Item>
</Accordion>
);
}

Related

extend Mantine Accordion Item

Mantine accordion specifies that its content should be only of type Accordion.Item (or, AccordionItem) - see the documentation for the children props. This means that even functions that actually return AccordionItem will not be listed.
So, this simple component will display only AccordionItem(s) that were instantiated inline, yet, not one returned from another function (see MyAccordionItem in this simple app).
The code:
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Accordion } from '#mantine/core';
const MyAccordionItem = ({children, label}) =>
<Accordion.Item label={label}>
{children}
</Accordion.Item>;
function App() {
return (
<div style={{width: 200}}>
<div>pre</div>
<Accordion>
<Accordion.Item label="section0">
<div>sec0.item1</div>
<div>sec0.item2</div>
<div>sec0.item3</div>
</Accordion.Item>
{/* Section 1 is not displayed because it is no of type Accordion.Item
<MyAccordionItem label="section 1">
<div>sec1.item1</div>
<div>sec1.item2</div>
<div>sec1.item3</div>
</MyAccordionItem>
<Accordion.Item label="section2">
<div>sec2.item1</div>
<div>sec2.item2</div>
<div>sec2.item3</div>
</Accordion.Item>
</Accordion>
<div>post</div>
</div>
);
}
render(<App />, document.getElementById('root'));
The reason is the filter function defined here, and used by the accordion here.
My questions are:
Do you know of any work around that helps assigning the same type (or, appearing to be an Accordion.Item when defining your own component?
On a larger scale, What do you think is the right approach from the library's perspective (in this case mantine), i.e. should it suffice in checking that the returned type is An accordion item?
I came across this same issue and found this GitHub issue in the Mantine repository with more information about creating child components that return AccordionItems.
rtivital (Mantine's creator) states:
Yes, currently that is not supported, it will require breaking changes, so Accordion and other similar components will be Migrated to context with next major release (5.0)
As to a work around, I haven't found anything yet other than creating a custom component for the content inside the AccordionItem and then wrapping that with the Mantine AccordionItem component inline via mapping or explicitly listing them.

How to change css when theme changes in React?

I am developing a library of react components and asked an important question. How to correctly change styles (css) when changing the application theme.
Appeal to those who already have experience in this and who can advise their approach or solution.
Now I'll tell you how it works for me:
I have my own themeProvider wrapped in a Context with the ability to change the theme.
When the theme changes in the provider, the changeCssVariables method is called.
export const changeCssVariables = (theme) => {
const root = document.querySelector(':root');
// root.style.setProperty('--default-color', 'orange');
const cssVariables = [
'color',
'background',
'color-uibutton',
'background-uibutton',
'box-shadow-uibutton',
'color-disabled-uibutton',
'background-disabled-uibutton',
'background-uiradiobutton',
'color-uiinputext',
'color-notes-uiinputext',
'color-subsection',
'background-subsection',
'box-shadow-subsection',
'alt-subsection',
'on-subsection',
'off-subsection',
];
cssVariables.forEach(element => {
root.style.setProperty(
`--default-${element}`,
`var(--theme-${theme}-${element})`
);
})
}
What happens in general: it has a global CSS with variables default, light and dark themes. When changing the theme, a method is called that changes the default variable to the variable of the selected theme.
Example css:
--default-color: var(--theme-light-color);
/* Themes */
--theme-light-color: #000;
--theme-dark-color: #fff;
I don't like that you have to pull in all the css and change it this way. What is the solution?
Thanks for the help!
Found a solution in using styled-components package
Created my wrapper as ThemeProvider (Context)

Design system: styles override using TailwindCSS

I am trying to create a Design System using ReactJS and TailwindCSS.
I created a default Button component with basic styling as follow:
import React from "react";
import classNames from "classnames";
const Button = React.forwardRef(
({ children, className = "", onClick }, ref) => {
const buttonClasses = classNames(
className,
"w-24 py-3 bg-red-500 text-white font-bold rounded-full"
);
const commonProps = {
className: buttonClasses,
onClick,
ref
};
return React.createElement(
"button",
{ ...commonProps, type: "button" },
children
);
}
);
export default Button;
I then use the Button in my page like:
import Button from "../src/components/Button";
export default function IndexPage() {
return (
<div>
<Button onClick={() => console.log("TODO")}>Vanilla Button</Button>
<div className="h-2" />
<Button
className="w-6 py-2 bg-blue-500 rounded-sm"
onClick={() => console.log("TODO")}
>
Custom Button
</Button>
</div>
);
}
This is what is displayed:
Some attributes are overridden like the background-color but some aren't (the rest).
The reason is the classes provided by TailwindCSS are written in an order where bg-blue-500 is placed after bg-red-500, therefore overriding it. On the other hand, the other classes provided in the custom button are written before the classes on the base button, therefore not overriding the styles.
This behavior is happening with TailwindCSS but might occurs with any other styling approach as far as the class order can produce this scenario.
Do you have any workaround / solution to enable this kind of customisation?
Here is a full CodeSanbox if needed.
One approach is to extract classes from your component using Tailwind's #apply in your components layer.
/* main.css */
#layer components {
.base-button {
#apply w-24 py-3 bg-red-500 text-white font-bold rounded-full;
}
}
// Button.js
const Button = React.forwardRef(({ children, className = "", onClick }, ref) => {
const buttonClasses = classNames("base-button", className);
// ...
);
This will extract the styles into the new base-button class, meaning they can easily be overwritten by the utility classes you pass to the Button component.
Another approach to create reusable React components using Tailwind is as follows..
Read this gist
https://gist.github.com/RobinMalfait/490a0560a7cfde985d435ad93f8094c5
for an excellent example.
Avoid using className as a prop. Otherwise, it'd be difficult for you to know what state your component is in. If you want to add an extra class, you can easily extend.
You need a helper for combining classname strings conditionally. Robert, the writer of this gist, shared the helper function also with us:
export function classNames(...classes: (false | null | undefined | string)[]) {
return classes.filter(Boolean).join(" ");
}
To have Tailwind CSS override material theming (or something else for that matter) one could apply !important to all tailwind utilities with configuration to module.exports.
The important option lets you control whether or not Tailwind’s utilities should be marked with !important. This can be really useful when using Tailwind with existing CSS that has high specificity selectors.
To generate utilities as !important, set the important key in your configuration options to true:
tailwind.config.js
module.exports = {
important: true
}
https://tailwindcss.com/docs/configuration#important
To solve, I recommend doing what Bootstrap does. Use a default class for your default button like:
.button {
width: 2rem;
background-color: red;
border-radius: 0.25rem;
}
Then when customizing a button you should apply classes that either come after the button class in your CSS file, or come in a different CSS file that is called after your default CSS file, or use the !important declaration.
Old answer
Use your browser developer tools to observe how your browser is loading CSS styles on an element. For example, in Chrome, right-click on the custom button and select "Inspect". A DevTools window will open and the element will be highlighted in the DOM.
On the right, you should have a Styles pane. There, you'll see a list of all the CSS styles being applied to the element. Styles with strikethroughs are being overridden by styles called by other CSS classes or inline styles.
In your case, the custom button has both the "CommonProps" classes and the classes you're adding in IndexPage. For example, both class w-6 and class w-24.
Class w-24 is overriding class w-6 because of CSS precedence. Read more about CSS precedence here. Check out rule #3 in the accepted answer. I think that's what's happening to you.
To solve, you may want to remove some classes from commonProps. Or use the !important declaration on some classes. This is the part of your design system that you need to think through. Look at how other systems like Bootstrap have done it.

with draft.js is it possible to create a custom block span with classname

I am using draft.js, and I have everything I need working except for one thing.
I want to be able to add a custom block option that will apply a span with a custom class (e.g. content) around the selected content in the editor.
Is this possible with draft-js custom blocks?
Any good examples out there? (didn't find anything when googling)
You can do it without wrapping text to the element with a custom class. You can style selected text with method RichUtils.toggleInlineStyle. More details described here.
Look at this working example - https://jsfiddle.net/x2gsp6ju/2/
Define customStyleMap object. Keys of this object should be unique names of your custom styles and values - objects with appropriate styles.
const customStyleMap = {
redBackground: {
backgroundColor: 'red'
},
underlined: {
textDecoration: 'underline',
fontSize: 26
},
};
Pass this object to customStyleMap property of Editor component:
<Editor
placeholder="Type away :)"
editorState={this.state.editorState}
onChange={this._handleChange}
customStyleMap={customStyleMap}
/>
In this example, I apply styles for selected text after click on appropriate buttons, I call this.applyCustomSTyles method and pass style-name as first argument. In this method I generate new editorState with RichUtils.toggleInlineStyles:
applyCustomStyles = (nameOfCustomStyle) => {
this._handleChange(
RichUtils.toggleInlineStyle(
this.state.editorState,
nameOfCustomStyle
)
);
}

Styling react-toolbox elements with className

I seem to be having some issues in regards to styling the components without using a theme. I just want to change a couple of colors without needing to create a new theme per element.
In this case, I just want to change the color of the bar to a brownish color and right now I have an input class as follows:
import style from './style.scss'
const TextInput = (props) => {
<Input className={style.textInput} {...props} />
}
And in my style.scss file:
.textInput {
.bar {
background-color: #663300;
}
}
Any help would be appreciated.
ClassName doesn't work like that.
You can't pass a Css style to a className, that is wrong.
Either pass the class names you want to apply as a string (in your case I guess it would be className="textInput bar") or you can create a className with classNames library (in any case the final result will be a string).
Just make sure you're styles are included in the page that the component is going to render and react will be smart enough to render the correct css class for each component.
As you can check in here ClassName is a string

Categories