All Projects → TinkoffCreditSystems → React Styling Hoc

TinkoffCreditSystems / React Styling Hoc

Licence: apache-2.0
Механизм темизации для React-компонентов, написанных с использованием CSS модулей.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to React Styling Hoc

tsstyled
A small, fast, and simple CSS-in-JS solution for React.
Stars: ✭ 52 (+108%)
Mutual labels:  style, theming
React Cssom
Css selector for React Components
Stars: ✭ 57 (+128%)
Mutual labels:  style, css-modules
css-flat-loader
CSS Flat 一种CSS模块化解决方案
Stars: ✭ 16 (-36%)
Mutual labels:  modules, css-modules
React Native Extended Stylesheet
Extended StyleSheets for React Native
Stars: ✭ 2,732 (+10828%)
Mutual labels:  style, theming
React Css Themr
Easy theming and composition for CSS Modules.
Stars: ✭ 582 (+2228%)
Mutual labels:  theming, css-modules
Gohack
Make temporary edits to your Go module dependencies
Stars: ✭ 739 (+2856%)
Mutual labels:  modules
Themekit
macOS theming library
Stars: ✭ 836 (+3244%)
Mutual labels:  theming
React Sizes
↔️ Hoc to easily map window sizes to props.
Stars: ✭ 726 (+2804%)
Mutual labels:  hoc
Remark Lint
Markdown code style linter
Stars: ✭ 718 (+2772%)
Mutual labels:  style
Go Modiff
Command line tool for diffing go module dependency changes between versions 📔
Stars: ✭ 24 (-4%)
Mutual labels:  modules
Gofumpt
A stricter gofmt
Stars: ✭ 904 (+3516%)
Mutual labels:  style
Styled System
⬢ Style props for rapid UI development
Stars: ✭ 7,126 (+28404%)
Mutual labels:  theming
React Lazy Load Image Component
React Component to lazy load images and components using a HOC to track window scroll position.
Stars: ✭ 755 (+2920%)
Mutual labels:  hoc
Braid Design System
Themeable design system for the SEEK Group
Stars: ✭ 888 (+3452%)
Mutual labels:  css-modules
Rspec Style Guide
Best practices for writing your specs!
Stars: ✭ 735 (+2840%)
Mutual labels:  style
Moui
🍕面向现代浏览器的 CSS 样式库
Stars: ✭ 21 (-16%)
Mutual labels:  style
Piral
Framework for next generation web apps using microfrontends. 🚀
Stars: ✭ 711 (+2744%)
Mutual labels:  modules
Cleanthesis
Clean Thesis is a clean, simple, and elegant LaTeX style (or template) for thesis documents.
Stars: ✭ 787 (+3048%)
Mutual labels:  style
Modules
📦 Modules package for Laravel
Stars: ✭ 900 (+3500%)
Mutual labels:  modules
Css Blocks
High performance, maintainable stylesheets.
Stars: ✭ 6,320 (+25180%)
Mutual labels:  css-modules

react-styling-hoc npm version

Механизм темизации для React-компонентов, написанных с использованием CSS модулей.
Позволяет переопределять стили для любых присутствующих в разметке компонента селекторов.

Механизм работы

Установка

 npm i react-styling-hoc

Явное задание темы

Button.jsx
import defaultStyles from './Button.css';
import styleHOC from 'react-styling-hoc';

class Button extends Component {
    render() {
        const { styles } = this.props;

        return <div className={styles.button}>Text</div>;
    }
}

const StylableButton = styleHOC(defaultStyles)(Button);

export default StylableButton;
Button.css
.button {
    background: #ffdd2d;
    color: #333;
    border: none;
}
myButton.theme.css
.button {
    background: red;
}
myCode.jsx
import Button from '@tinkoff-ui/button';
import themeStyles from 'myButton.theme.css';

const MyButton = props => <Button {...props} themeStyles={themeStyles} />;

const MyComponent = () => <div>
    <div>Something special</div>
    <MyButton/>
</div>;

Сброс стандартных стилей

Если вам не нужны стандартные стили компонента, и вы хотите их написать сами с нуля, то с помощью пропа resetDefaultStyles можно их сбросить.

const MyButton = props => <Button
    {...props}
    themeStyles={themeStyles}
    resetDefaultStyles
/>;

Темизация через контекст

Бывают случаи, когда мы не можем внедриться в чужую часть кода.

Например, мы имеем некоторый компонент InputGroup, который использует в себе темизируемый компонент Input. Явно заменить <Input> на <ThemedInput> мы не можем.

В таких случаев предусмотрена темизация через контекст, задать который можно через компонент ThemeProvider.

InputGroup.jsx
import Group from '@tinkoff-ui/group';
import Input from '@tinkoff-ui/input';


const InputGroup = () => <Group>
    <Input/>
    <Input/>
    <Input/>
</Group>;

export default InputGroup;
myCode.jsx
import InputGroup from '@tinkoff-ui/inputGroup';
import Input from '@tinkoff-ui/input';
import { ThemeProvider } from 'react-styling-hoc';

import themeStyles from 'myInput.theme.css';

const MyComponent = () => <div>
    <div>Something special</div>
    <ThemeProvider
        themes={[
            {
                component: Input,
                themeStyles
            }
        ]}
    >
        <InputGroup/>
    </ThemeProvider>
</div>;

Ура, мы великолепны, теперь все инпуты внутри ThemeProvider будут выглядеть иначе!

ThemeProvider имеет единственный проп themes, принимающий в себя объект, ключами в котором являются названия темизирумых компонентов, а значениями - объекты с пропсами theme HOC'а.

ThemeProvider можно вкладывать друг в друга, одинаковые темы будут переопределяться, а разные сохраняться.

Инъекция зависимостей

Бывают случаи, когда переопределять нужно не только стили, но и целые части компонента или разметки. Например, мы решили провести A/B-тестирование полей ввода даты, и нам необходимо заменить использование <Calendar> на <NewCalendar> внутри компонента <DateInput>.

Если мы заранее предусмотрим возможность переопределения, то аналогично стилям через Theme HOC и <ThemeProvider> мы можем передать в компонент новый компонент календаря.

InputDate.jsx
 import Calendar from '@tinkoff-ui//calendar';
 import Input from '@tinkoff-ui/input';
 import styleHOC from 'react-styling-hoc';

 const InputDate = styleHOC()(({ themeBlocks }) => {
     const CalendarElem = themeBlocks && themeBlocks.Calendar || Calendar;

     return <div>
         <Input/>
         <CalendarElem/>
     </div>;
 });
 
 export default InputDate;
myCode.jsx
import InputDate from '@tinkoff-ui/inputDate';
import { ThemeProvider } from '@tinkoff-ui/style-hoc';
import NewCalender from './NewCalender.jsx';


const MyComponent = () => <div>
    <div>Something special</div>
    <ThemeProvider
        themes={[
            {
                component: InputDate,
                themeBlocks: {
                    Calendar: NewCalender
                }
            }
        ]}
    >
        <InputDate/>
    </ThemeProvider>
</div>;

Повышение веса стилей

Все cелекторы с переопределяющими стилями должны всегда иметь большую специфичность, чем базовые. Для этого можно собственноручно повышать ее или воспользоваться небольшим postcss-плагином.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].