├── .babelrc ├── .eslintignore ├── .eslintrc ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml └── workflows │ └── lint-and-test.yml ├── .gitignore ├── .npmignore ├── .nvmrc ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── jest.config.js ├── package.json ├── src ├── components │ ├── Case.tsx │ ├── Default.tsx │ ├── For.tsx │ ├── Switch.tsx │ └── tests │ │ ├── For.test.tsx │ │ ├── Switch.test.tsx │ │ └── __snapshots__ │ │ ├── For.test.tsx.snap │ │ └── Switch.test.tsx.snap ├── directives │ ├── elements.ts │ ├── index.ts │ ├── makeDirective.ts │ └── tests │ │ ├── __snapshots__ │ │ └── dir.snapshot.test.tsx.snap │ │ ├── dir.snapshot.test.tsx │ │ └── makeDirective.test.tsx ├── helpers │ └── test-helpers.ts ├── hooks │ ├── tests │ │ └── useClassName.test.ts │ └── useClassName.ts ├── index.ts └── types │ ├── classes.ts │ ├── directive.ts │ ├── for.ts │ └── switch.ts ├── tsconfig.eslint.json ├── tsconfig.json └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"], 3 | "plugins": [] 4 | } -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | jest.config.js 3 | node_modules -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "airbnb", 4 | "airbnb-typescript", 5 | "airbnb/hooks", 6 | "plugin:@typescript-eslint/recommended", 7 | "plugin:prettier/recommended", 8 | "prettier" 9 | ], 10 | "plugins": ["react", "@typescript-eslint"], 11 | "env": { 12 | "browser": true, 13 | "es6": true, 14 | "jest": false 15 | }, 16 | "parser": "@typescript-eslint/parser", 17 | "parserOptions": { 18 | "ecmaFeatures": { 19 | "jsx": true 20 | }, 21 | "ecmaVersion": 2020, 22 | "sourceType": "module", 23 | "project": "./tsconfig.eslint.json" 24 | }, 25 | "rules": { 26 | "@typescript-eslint/no-explicit-any": "off", 27 | "@typescript-eslint/no-non-null-assertion": "off", 28 | "react/function-component-definition": "off", 29 | "import/extensions": ["off"], 30 | "react/no-unstable-nested-components": ["warn", { "allowAsProps": true }], 31 | "import/no-extraneous-dependencies": [ 32 | "warn", 33 | { 34 | "devDependencies": [ 35 | "**/*.test.ts", 36 | "**/*.spec.ts", 37 | "**/*.test.tsx", 38 | "**/*.spec.tsx" 39 | ], 40 | "optionalDependencies": false, 41 | "peerDependencies": true 42 | } 43 | ], 44 | "comma-dangle": "off", 45 | "import/no-cycle": "off", 46 | "jsx-a11y/control-has-associated-label": "off", 47 | "jsx-a11y/label-has-associated-control": "off", 48 | "jsx-a11y/click-events-have-key-events": "off", 49 | "react/require-default-props": "off", 50 | "jsx-a11y/interactive-supports-focus": "off", 51 | "@typescript-eslint/no-use-before-define": "off", 52 | "@typescript-eslint/no-unused-expressions": ["error"], 53 | "no-plusplus": "off", 54 | "react/destructuring-assignment": "off", 55 | "react-hooks/exhaustive-deps": "off", 56 | "import/prefer-default-export": "off", 57 | "react/prop-types": "off", 58 | "no-unused-vars": "error", 59 | "no-console": "warn", 60 | "no-underscore-dangle": "off", 61 | "react/jsx-props-no-spreading": "off", 62 | "prettier/prettier": [ 63 | "error", 64 | { 65 | "endOfLine": "auto" 66 | } 67 | ] 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | # Enable version updates for npm 9 | - package-ecosystem: 'npm' 10 | # Look for `package.json` and `lock` files in the `root` directory 11 | directory: '/' 12 | # Check the npm registry for updates every day (weekdays) 13 | target-branch: 'dependencies' 14 | schedule: 15 | interval: 'daily' 16 | -------------------------------------------------------------------------------- /.github/workflows/lint-and-test.yml: -------------------------------------------------------------------------------- 1 | name: Lint and Test 2 | 3 | on: 4 | push: 5 | branches: [ master, develop, dependencies ] 6 | pull_request: 7 | branches: [ master, develop, dependencies ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | - uses: actions/setup-node@v3 16 | with: 17 | node-version: 16 18 | - run: yarn 19 | - run: yarn lint 20 | - run: yarn test 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | coverage 4 | src/Playground.tsx -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | coverage 3 | src/Playground.tsx 4 | .eslintrc 5 | .nvmrc 6 | jest.config.js 7 | tsconfig.json 8 | tsconfig.eslint.json 9 | .eslintignore 10 | .babelrc 11 | .github 12 | LICENSE 13 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v16.15.0 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | mkhstar. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Musah Kusi Hussein 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # react-directive 3 | 4 | > A conditional, className and listing directive for react apps 5 | 6 | [![NPM](https://img.shields.io/npm/v/react-directive.svg)](https://www.npmjs.com/package/react-directive) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) 7 | 8 | ## Install 9 | 10 | ```bash 11 | # npm 12 | npm i react-directive 13 | 14 | # yarn 15 | yarn add react-directive 16 | ``` 17 | 18 | # Introduction 19 | `react-directive` is a library for creating conditional or listing directives in a react app. 20 | It takes a lot of inspiration from [Vue.js'](https://vuejs.org/) conditional, class bindings and listing directives such as `v-if`, `v-for`, and `:class`. 21 | Its two main purposes are listed below. 22 | - To avoid the headache of using conditional (ternary) operators or higher order array methods such as map for list rendering. 23 | - To keep JSX clean and concise. 24 | 25 | # Usage 26 | To use `react-directive` import it to your component. 27 | ```jsx 28 | import React from 'react'; 29 | import directive from 'react-directive'; 30 | 31 | const Component = () => { 32 | return ( 33 | // This is the same as a div element but has more features like dirIf, dirFor, extended className etc. 34 | 35 | { /* Any children for the div element */ } 36 | 37 | ); 38 | } 39 | ``` 40 | 41 | # Conditional Rendering 42 | 43 | `react-directive` provides directives such as `dirIf`, `dirShow` and components ``, `` `` to render (show) or remove (hide) an element from the page. 44 | 45 | 46 | ## Prop `dirIf` 47 | 48 | The prop `dirIf` is used to conditionally render a block. The block will only be rendered if the directive’s expression returns a **truthy** value (Check out truthy and falsy values in javascript [here](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)). It works like `v-if` for `Vuejs` and `ngIf` for angular. 49 | 50 | Currently, there is no support for `else` and `else-if` yet. ( You can use the `` component to handle such cases. More on that later ). 51 | 52 | **Note**: `undefined` is the only exceptional falsy value that evaluates to `true` because the default value for `dirIf` is true 53 | 54 | ### Usage 55 | 56 | The example component below renders a `div` element only if the name's length is greater than `4` otherwise it will just render a `null` value. If you want to keep the `node` and only toggle style's display value, use the `dirShow` prop instead. 57 | 58 | ```jsx 59 | import React, { useState } from 'react'; 60 | import directive from 'react-directive'; 61 | 62 | const Component = () => { 63 | const [currentName, setCurrentName] = useState('Musah'); 64 | 65 | return ( 66 | 4}> 67 | Div contents 68 | 69 | ); 70 | } 71 | /* 72 | When dirIf is truthy, it renders 73 |
Div contents
74 | 75 | When dirIf is falsy, it renders nothing 76 | */ 77 | ``` 78 | 79 | 80 | ## Prop `dirShow` 81 | 82 | The prop `dirShow` is used to conditionally show a block. The block will only be shown if the directive’s expression returns a **truthy** value. It works like `v-show` for `Vuejs`. 83 | 84 | **Note**: `dirShow` takes precedence to any another display for styles. For example if you set the display to block and `dirShow` is `false`, it will still hide the element. 85 | **Note**: `undefined` is the only exceptional falsy value that evaluates to `true` because the default value for `dirShow` is true 86 | 87 | ### Usage 88 | The example component below shows a `div` element only if the name's length is greater than `4` otherwise it will hide the `div` element by add the `display:none` to its styles. 89 | 90 | 91 | 92 | ```jsx 93 | import React, { useState } from 'react'; 94 | import directive from 'react-directive'; 95 | 96 | const Component = () => { 97 | const [currentName, setCurrentName] = useState('Musah'); 98 | 99 | return ( 100 | 4}> 101 | Div contents 102 | 103 | ); 104 | } 105 | /* 106 | When dirShow is truthy, it renders 107 |
Div contents
108 | 109 | When dirShow is falsy, it renders 110 |
Div contents
111 | */ 112 | ``` 113 | 114 | ## Component `` 115 | 116 | The `` component is used to conditionally render a `` that resolves to a truthy value. Otherwise it renders `` (If it exists). 117 | 118 | ### Usage 119 | The example component below shows the `div` element with contents `Case 2` because it is the first case that resolves to a truthy value. 120 | 121 | Note that the `when` prop for the `` component supports either a (truthy | falsy) value or a function that returns a (truthy | falsy) value. 122 | It is recommended to use the function version if the calculation is intensive. This helps in short circuiting (lazy evaluation) when the case is not reached. 123 | 124 | 125 | 126 | ```jsx 127 | import React, { useState } from 'react'; 128 | import { Switch, Case, Default } from 'react-directive'; 129 | 130 | const Component = props => { 131 | const [currentName, setCurrentName] = useState('Musah'); 132 | 133 | // This makes it more concise to render an element instead of using nested ternary operator. 134 | // Fun fact: I was getting lots of eslint problems because of using ternary operators which was one of my main motivations for building this library. 135 | return ( 136 | 137 | 138 |
Case 1
139 |
140 | 4}> 141 |
Case 2
142 |
143 | {/* The case below resolves to true but the case above will render because it is the first match */} 144 | 145 |
Case 3
146 |
147 | 148 |
Default
149 |
150 |
151 | ); 152 | } 153 | /* 154 | renders 155 |
Case 2
156 | */ 157 | ``` 158 | 159 | 160 | # Class Names 161 | A common need for data binding is manipulating an element's class list. 162 | `react-directive` provides the hook `useClassName` and an extended version of the `className` prop to handle this issue 163 | 164 | ## Hook `useClassName` 165 | A simple hook for generating class names. 166 | 167 | ### Usage 168 | The hook takes in two optional parameters: `classes` and `deps` (dependencies). 169 | 170 | - `classes` can be a string, an array of strings, an object with class names as keys and truthy values, or an array of such objects. 171 | 172 | - `deps` is an optional dependencies array that tells the hook to re-run when one of its values changes. 173 | 174 | **Note**: When dependencies are not passed, it will fallback to re-calculate the class names based on the classes argument itself. Also it is advisable to pass an array of primitive values or cached values. So that it doesn't re-calculate unnecessarily. Think of it like a `useEffect` dependency. 175 | 176 | Here are some basic examples: 177 | 178 | ```tsx 179 | import { useClassName } from 'react-directive'; 180 | 181 | function Component() { 182 | const className = useClassName({ 183 | active: true, 184 | disabled: false, 185 | }); 186 | 187 | return
Contents
; 188 | } 189 | 190 | // Renders
Contents
191 | ``` 192 | 193 | You can also pass an array of objects, strings, or a combination of both: 194 | 195 | ```tsx 196 | import { useState } from 'react' 197 | import { useClassName } from 'react-directive'; 198 | 199 | function Component() { 200 | const [isActive, setIsActive] = useState(true); 201 | const [isDisabled, setIsDisabled] = useState(false); 202 | const className = useClassName([ 203 | 'highlighted', 204 | { active: isActive, disabled: isDisabled }, 205 | ], [isActive, isDisabled]); // Optional deps to tell it to re-calculate based on isActive and isDisabled values 206 | 207 | return
Contents
; 208 | } 209 | // Renders
Contents
210 | // This is useful if you have some other classNames that doesn't have to react to any value 211 | ``` 212 | 213 | ## Prop `className` 214 | `react-directive` extends the default className of React to support what the `useClassName` hook supports above. To pass the dependencies, use `classNameDeps` props. 215 | 216 | Here are some basic examples: 217 | 218 | ```tsx 219 | import { useState } from 'react' 220 | import directive from 'react-directive'; 221 | 222 | function Component() { 223 | const [isActive, setIsActive] = useState(true); 224 | const [isDisabled, setIsDisabled] = useState(false); 225 | 226 | return Contents; 227 | } 228 | // Renders
Contents
229 | // classNameDeps is optional but makes it more efficient and performant. 230 | ``` 231 | 232 | 233 | # List Rendering 234 | 235 | `react-directive` provides the directive `dirFor` and the component `` to generate lists. This makes it more readable than using `Array.prototype.map`. 236 | 237 | 238 | ## Usage 239 | The `` component takes in an object with two properties: `each` and `children` 240 | 241 | - `each` is an array of items that you want to render. 242 | 243 | - `children` is a function that takes in two arguments: `value` and `index`. `value` is the current item in the `each` array and `index` is its index in the array. 244 | 245 | **Note**: Make sure to pass a unique key prop to the elements rendered by the children function. This is important for React to keep track of the elements and render updates efficiently. 246 | 247 | 248 | Here is a basic example: 249 | 250 | ```tsx 251 | import { For } from 'react-directive'; 252 | 253 | function Component() { 254 | const items = ['Item 1', 'Item 2', 'Item 3']; 255 | 256 | return ( 257 | 258 | {(value, index) =>
{value}
} 259 |
260 | ); 261 | } 262 | 263 | /* renders 264 |
Item 1
265 |
Item 2
266 |
Item 3
267 | */ 268 | ``` 269 | 270 | You might have noticed that we are passing a function. It is important to know that if you want the values of the elements in the list you passed, you must pass a function to be able to access them. This works like ``. 271 | 272 | ## Prop `dirFor` 273 | `react-directive` includes a prop that takes an `array` of items you want to render. The children prop is a function or React node that is called for each item in the array. The function takes in two arguments: `currentItem` and `index`. `currentItem` is the current item in the `dirFor` array and `index` is its index in the array. 274 | 275 | **Note**: Make sure to pass a unique key prop to the elements rendered by the children function using `dirKey` (More later). This is important for React to keep track of the elements and render updates efficiently. It fallsback to using the `index` of the item if not provided 276 | 277 | Here is a basic example: 278 | 279 | ```tsx 280 | import directive from 'react-directive'; 281 | 282 | function Component() { 283 | const items = ['Item 1', 'Item 2', 'Item 3']; 284 | 285 | return ( 286 | // this means the current item. Used because the items are unique. If they are not 287 | {(currentItem) => currentItem} 288 | ); 289 | } 290 | 291 | /* renders 292 |
Item 1
293 |
Item 2
294 |
Item 3
295 | */ 296 | ``` 297 | 298 | 299 | # Other props 300 | 301 | ## Prop `dirKey` 302 | The `dirKey` prop is used to specify the key of the current element which is in the loop while using `dirFor`. 303 | 304 | - It can take `this`, which means the current item should be used as a key. **Note**: use this for only primitive values that you know will be unique in the list. 305 | - It can take any other string. When any other string is specified, it will use that to find the index in the current item according to the name. It will assume that the current item is an object. If null or undefined is returned, it will fallback to the index 306 | - It can take in a function that returns the key 307 | 308 | ## Prop `dirRef` 309 | The `dirRef` prop is used instead of the standard ref prop for directives. The `ref` prop will not work when using directives. 310 | 311 | Here is a basic example: 312 | 313 | ```tsx 314 | import { useRef } from 'react'; 315 | import directive from 'react-directive'; 316 | 317 | function Component() { 318 | const inputRef = useRef(null); 319 | const focusInput = () => { 320 | inputRef.current.focus(); 321 | } 322 | 323 | return ( 324 | 325 | 326 | 327 | 328 | ); 329 | } 330 | ``` 331 | 332 | 333 | # Pull Requests 334 | 335 | Pull requests are welcome. Open pull requests to the develop branch and make sure it all lint and tests are passing. 336 | 337 | # License 338 | 339 | MIT © [Musah Kusi Hussein](https://github.com/mkhstar) 340 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | // The root of your source code, typically /src 3 | // `` is a token Jest substitutes 4 | roots: ["/src"], 5 | 6 | // Jest transformations -- this adds support for TypeScript 7 | // using ts-jest 8 | transform: { 9 | "^.+\\.tsx?$": "ts-jest", 10 | }, 11 | 12 | // Runs special logic, such as cleaning up components 13 | // when using React Testing Library and adds special 14 | // extended assertions to Jest 15 | setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"], 16 | 17 | // Test spec file resolution pattern 18 | // Matches parent folder `__tests__` and filename 19 | // should contain `test` or `spec`. 20 | testRegex: ".*\\.(spec|test)\\.tsx?$", 21 | testEnvironment: "jsdom", 22 | 23 | // Module file extensions for importing 24 | moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], 25 | }; 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-directive", 3 | "version": "2.0.0", 4 | "description": "A conditional, className and listing directive for react apps", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/mkhstar/react-directive" 8 | }, 9 | "main": "dist/index.js", 10 | "scripts": { 11 | "build": "rm -rf ./dist && tsc", 12 | "prepublishOnly": "npm run build", 13 | "test-only": "jest", 14 | "test": "jest --verbose --coverage", 15 | "test-output": "jest --verbose --coverage --coverageDirectory='coverage'", 16 | "test:watch": "jest --verbose --watch", 17 | "lint-fix": "eslint --fix src/.", 18 | "lint": "eslint src/." 19 | }, 20 | "keywords": [ 21 | "react", 22 | "className", 23 | "classList", 24 | "directive", 25 | "dirIf", 26 | "dirShow", 27 | "dirFor", 28 | "loop", 29 | "condition", 30 | "listing" 31 | ], 32 | "author": "Kusi Musah Hussein", 33 | "license": "MIT", 34 | "devDependencies": { 35 | "@testing-library/jest-dom": "^5.16.5", 36 | "@testing-library/react": "^14.0.0", 37 | "@types/jest": "^29.4.0", 38 | "@types/node": "^18.15.11", 39 | "@types/react": "^18.0.27", 40 | "@types/react-dom": "^18.0.10", 41 | "@types/react-test-renderer": "^18.0.0", 42 | "@typescript-eslint/eslint-plugin": "^5.48.2", 43 | "@typescript-eslint/parser": "^5.48.2", 44 | "eslint": "^8.32.0", 45 | "eslint-config-airbnb": "^19.0.4", 46 | "eslint-config-airbnb-typescript": "^17.0.0", 47 | "eslint-config-prettier": "^8.6.0", 48 | "eslint-plugin-import": "^2.27.5", 49 | "eslint-plugin-jsx-a11y": "^6.7.1", 50 | "eslint-plugin-prettier": "^4.2.1", 51 | "eslint-plugin-react": "^7.32.1", 52 | "eslint-plugin-react-hooks": "^4.6.0", 53 | "jest": "^29.4.1", 54 | "jest-environment-jsdom": "^29.4.1", 55 | "prettier": "^2.8.3", 56 | "react": "^18.2.0", 57 | "react-dom": "^18.2.0", 58 | "react-test-renderer": "^18.2.0", 59 | "sass": "^1.32.0", 60 | "ts-jest": "^29.0.5", 61 | "typescript": "^5.0.3" 62 | }, 63 | "peerDependencies": { 64 | "react": ">=16.8.0" 65 | }, 66 | "browserslist": [ 67 | ">0.2%", 68 | "not ie <= 11", 69 | "not op_mini all" 70 | ], 71 | "dependencies": {} 72 | } 73 | -------------------------------------------------------------------------------- /src/components/Case.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { CaseProps } from "../types/switch"; 3 | 4 | export class Case extends React.Component { 5 | render() { 6 | const { when, children } = this.props; 7 | return when ? children : null; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/components/Default.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { DefaultProps } from "../types/switch"; 3 | 4 | export class Default extends React.Component { 5 | render() { 6 | return this.props.children; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/components/For.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { ForProps } from "../types/for"; 3 | 4 | export class For extends React.Component> { 5 | render() { 6 | return this.props.each.map((value, index) => 7 | this.props.children(value, index) 8 | ); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/components/Switch.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from "react"; 2 | import { SwitchProps } from "../types/switch"; 3 | 4 | export const Switch: React.FC = ({ children }) => { 5 | let caseToRender: ReactNode | null = null; 6 | 7 | React.Children.forEach(children, (child) => { 8 | if (caseToRender) return; 9 | 10 | const { props } = child; 11 | if ( 12 | "when" in props && 13 | (typeof props.when === "function" ? props.when() : props.when) 14 | ) { 15 | caseToRender = child; 16 | return; 17 | } 18 | if (!("when" in props)) caseToRender = child; 19 | }); 20 | 21 | return caseToRender; 22 | }; 23 | -------------------------------------------------------------------------------- /src/components/tests/For.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { render } from "@testing-library/react"; 3 | import { snapshotTest } from "../../helpers/test-helpers"; 4 | import { For } from "../For"; 5 | 6 | describe("", () => { 7 | it("renders correct number of children", () => { 8 | const each = [1, 2, 3]; 9 | const { queryAllByTestId } = render( 10 | 11 | {(value) => ( 12 |
13 | {value} 14 |
15 | )} 16 |
17 | ); 18 | 19 | expect(queryAllByTestId("child").length).toBe(each.length); 20 | }); 21 | 22 | it("renders children with correct values", () => { 23 | const each = [1, 2, 3]; 24 | const { queryAllByText } = render( 25 | {(value) =>
{value}
}
26 | ); 27 | 28 | each.forEach((value) => { 29 | expect(queryAllByText(value.toString()).length).toBe(1); 30 | }); 31 | }); 32 | 33 | it("does not render anything if `each` is an empty array", () => { 34 | const each: Array = []; 35 | const { queryAllByTestId } = render( 36 | {(value) =>
{value}
}
37 | ); 38 | 39 | expect(queryAllByTestId("child").length).toBe(0); 40 | }); 41 | 42 | it("passes the correct value and index to children", () => { 43 | const each = [ 44 | { id: 1, name: "Musah", school: "Hacettepe", from: "Kumasi" }, 45 | { id: 2, name: "Shakino", school: "Okess", from: "Oman" }, 46 | { id: 3, name: "Sala", school: "UOEW", from: "Kumasi" }, 47 | ]; 48 | const { queryAllByText } = render( 49 | 50 | {(value, index) => ( 51 |
{`Name: ${value.name}, School ${value.school}, From ${value.from}, Index: ${index}`}
54 | )} 55 |
56 | ); 57 | 58 | each.forEach((value, index) => { 59 | expect( 60 | queryAllByText( 61 | `Name: ${value.name}, School ${value.school}, From ${value.from}, Index: ${index}` 62 | ).length 63 | ).toBe(1); 64 | }); 65 | }); 66 | 67 | it("passes the correct value and index to children with multiple nodes", () => { 68 | const each = [{ name: "Musah", school: "Hacettepe", from: "Kumasi" }]; 69 | const { queryByTestId } = render( 70 | 71 | {(value, index) => ( 72 | 73 |

Name: {value.name}

74 |

School: {value.school}

75 |

From: {value.from}

76 |

Index: {index}

77 |
78 | )} 79 |
80 | ); 81 | expect(queryByTestId("name")?.textContent).toEqual("Name: Musah"); 82 | expect(queryByTestId("school")?.textContent).toEqual("School: Hacettepe"); 83 | expect(queryByTestId("from")?.textContent).toEqual("From: Kumasi"); 84 | expect(queryByTestId("index")?.textContent).toEqual("Index: 0"); 85 | }); 86 | }); 87 | 88 | describe(" snapshots", () => { 89 | it("matches the snapshot with an array of numbers", () => { 90 | snapshotTest( 91 | 92 | {(value, index) =>
{value}
} 93 |
94 | ); 95 | }); 96 | 97 | it("matches the snapshot with an array of strings", () => { 98 | snapshotTest( 99 | 100 | {(value, index) =>
{value}
} 101 |
102 | ); 103 | }); 104 | 105 | it("matches the snapshot with an empty array", () => { 106 | snapshotTest( 107 | {(value, index) =>
{value}
}
108 | ); 109 | }); 110 | 111 | it("passes the correct value and index to children", () => { 112 | const each = [ 113 | { id: 1, name: "Musah", school: "Hacettepe", from: "Kumasi" }, 114 | { id: 2, name: "Shakino", school: "Okess", from: "Oman" }, 115 | { id: 3, name: "Sala", school: "UOEW", from: "Kumasi" }, 116 | ]; 117 | 118 | snapshotTest( 119 | 120 | {(value, index) => ( 121 |
{`Name: ${value.name}, School ${value.school}, From ${value.from}, Index: ${index}`}
124 | )} 125 |
126 | ); 127 | }); 128 | }); 129 | -------------------------------------------------------------------------------- /src/components/tests/Switch.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { render, cleanup } from "@testing-library/react"; 3 | import { snapshotTest, truthyFalsyMap } from "../../helpers/test-helpers"; 4 | import { Switch } from "../Switch"; 5 | import { Case } from "../Case"; 6 | import { Default } from "../Default"; 7 | 8 | afterEach(cleanup); 9 | 10 | describe("Switch, Case and Default", () => { 11 | describe("", () => { 12 | it("renders the first Case whose when prop returns truthy value", () => { 13 | truthyFalsyMap.forEach((value) => { 14 | const { getByText, queryByText, unmount } = render( 15 | 16 | 17 |
Case 1
18 |
19 | 20 |
Case 2
21 |
22 | 23 |
Case 3
24 |
25 | 26 |
Default
27 |
28 |
29 | ); 30 | expect(queryByText("Case 1")).toBeNull(); 31 | expect(getByText("Case 2")).toBeInTheDocument(); 32 | expect(queryByText("Case 3")).toBeNull(); 33 | expect(queryByText("Default")).toBeNull(); 34 | unmount(); 35 | }); 36 | }); 37 | 38 | it("renders the first Case whose when prop function returns true", () => { 39 | truthyFalsyMap.forEach((value) => { 40 | const { getByText, queryByText, unmount } = render( 41 | 42 | value.falsy}> 43 |
Case 1
44 |
45 | value.truthy}> 46 |
Case 2
47 |
48 | 49 |
Case 3
50 |
51 | 52 |
Default
53 |
54 |
55 | ); 56 | expect(queryByText("Case 1")).toBeNull(); 57 | expect(getByText("Case 2")).toBeInTheDocument(); 58 | expect(queryByText("Case 3")).toBeNull(); 59 | expect(queryByText("Default")).toBeNull(); 60 | unmount(); 61 | }); 62 | }); 63 | 64 | it("renders the Default component if no Case's when prop returns true", () => { 65 | const { getByText, queryByText, unmount } = render( 66 | 67 | 68 |
Case 1
69 |
70 | 71 |
Case 2
72 |
73 | 74 |
Default
75 |
76 |
77 | ); 78 | expect(queryByText("Case 1")).toBeNull(); 79 | expect(queryByText("Case 2")).toBeNull(); 80 | expect(getByText("Default")).toBeInTheDocument(); 81 | unmount(); 82 | }); 83 | }); 84 | 85 | describe("", () => { 86 | it("renders children if when prop returns true", () => { 87 | const { getByText, unmount } = render( 88 | 89 |
Case
90 |
91 | ); 92 | expect(getByText("Case")).toBeInTheDocument(); 93 | unmount(); 94 | }); 95 | 96 | it("renders children if when prop function returns true", () => { 97 | const { getByText, unmount } = render( 98 | true}> 99 |
Case
100 |
101 | ); 102 | expect(getByText("Case")).toBeInTheDocument(); 103 | unmount(); 104 | }); 105 | 106 | it("does not render children if when prop returns false", () => { 107 | const { queryByText, unmount } = render( 108 | 109 |
Case
110 |
111 | ); 112 | expect(queryByText("Case")).toBeNull(); 113 | unmount(); 114 | }); 115 | }); 116 | 117 | describe("", () => { 118 | it("Should render whatever child it receives", () => { 119 | const { getByText, unmount } = render( 120 | 121 |
Default
122 |
123 | ); 124 | expect(getByText("Default")).toBeInTheDocument(); 125 | unmount(); 126 | }); 127 | }); 128 | }); 129 | 130 | describe(" snapshots", () => { 131 | it("matches the snapshot with the matching case", () => { 132 | snapshotTest( 133 | 134 | 135 |
Case 1
136 |
137 | 138 |
Case 2
139 |
140 |
141 | ); 142 | snapshotTest( 143 | 144 | 145 |
Case 1
146 |
147 | 148 |
Case 2
149 |
150 | 151 |
Case 3
152 |
153 | 154 |
Default
155 |
156 |
157 | ); 158 | }); 159 | 160 | it("matches the snapshot with the default case", () => { 161 | snapshotTest( 162 | 163 | 164 |
Case 1
165 |
166 | 167 |
Default case
168 |
169 |
170 | ); 171 | snapshotTest( 172 | 173 | 174 |
Case 1
175 |
176 |
, 177 | "No default case" 178 | ); 179 | }); 180 | }); 181 | -------------------------------------------------------------------------------- /src/components/tests/__snapshots__/For.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` snapshots matches the snapshot with an array of numbers 1`] = ` 4 | [ 5 |
6 | 1 7 |
, 8 |
9 | 2 10 |
, 11 |
12 | 3 13 |
, 14 | ] 15 | `; 16 | 17 | exports[` snapshots matches the snapshot with an array of strings 1`] = ` 18 | [ 19 |
20 | a 21 |
, 22 |
23 | b 24 |
, 25 |
26 | c 27 |
, 28 | ] 29 | `; 30 | 31 | exports[` snapshots matches the snapshot with an empty array 1`] = `null`; 32 | 33 | exports[` snapshots passes the correct value and index to children 1`] = ` 34 | [ 35 |
36 | Name: Musah, School Hacettepe, From Kumasi, Index: 0 37 |
, 38 |
39 | Name: Shakino, School Okess, From Oman, Index: 1 40 |
, 41 |
42 | Name: Sala, School UOEW, From Kumasi, Index: 2 43 |
, 44 | ] 45 | `; 46 | -------------------------------------------------------------------------------- /src/components/tests/__snapshots__/Switch.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` snapshots matches the snapshot with the default case 1`] = ` 4 |
5 | Default case 6 |
7 | `; 8 | 9 | exports[` snapshots matches the snapshot with the default case: No default case 1`] = `null`; 10 | 11 | exports[` snapshots matches the snapshot with the matching case 1`] = ` 12 |
13 | Case 1 14 |
15 | `; 16 | 17 | exports[` snapshots matches the snapshot with the matching case 2`] = ` 18 |
19 | Case 2 20 |
21 | `; 22 | -------------------------------------------------------------------------------- /src/directives/elements.ts: -------------------------------------------------------------------------------- 1 | // From styled-components 2 | 3 | export const elements = [ 4 | "a", 5 | "abbr", 6 | "address", 7 | "area", 8 | "article", 9 | "aside", 10 | "audio", 11 | "b", 12 | "base", 13 | "bdi", 14 | "bdo", 15 | "big", 16 | "blockquote", 17 | "body", 18 | "br", 19 | "button", 20 | "canvas", 21 | "caption", 22 | "cite", 23 | "code", 24 | "col", 25 | "colgroup", 26 | "data", 27 | "datalist", 28 | "dd", 29 | "del", 30 | "details", 31 | "dfn", 32 | "dialog", 33 | "div", 34 | "dl", 35 | "dt", 36 | "em", 37 | "embed", 38 | "fieldset", 39 | "figcaption", 40 | "figure", 41 | "footer", 42 | "form", 43 | "h1", 44 | "h2", 45 | "h3", 46 | "h4", 47 | "h5", 48 | "h6", 49 | "head", 50 | "header", 51 | "hgroup", 52 | "hr", 53 | "html", 54 | "i", 55 | "iframe", 56 | "img", 57 | "input", 58 | "ins", 59 | "kbd", 60 | "keygen", 61 | "label", 62 | "legend", 63 | "li", 64 | "link", 65 | "main", 66 | "map", 67 | "mark", 68 | "menu", 69 | "menuitem", 70 | "meta", 71 | "meter", 72 | "nav", 73 | "noscript", 74 | "object", 75 | "ol", 76 | "optgroup", 77 | "option", 78 | "output", 79 | "p", 80 | "param", 81 | "picture", 82 | "pre", 83 | "progress", 84 | "q", 85 | "rp", 86 | "rt", 87 | "ruby", 88 | "s", 89 | "samp", 90 | "script", 91 | "section", 92 | "select", 93 | "small", 94 | "source", 95 | "span", 96 | "strong", 97 | "style", 98 | "sub", 99 | "summary", 100 | "sup", 101 | "table", 102 | "tbody", 103 | "td", 104 | "textarea", 105 | "tfoot", 106 | "th", 107 | "thead", 108 | "time", 109 | "title", 110 | "tr", 111 | "track", 112 | "u", 113 | "ul", 114 | "use", 115 | "var", 116 | "video", 117 | "wbr", // SVG 118 | "circle", 119 | "clipPath", 120 | "defs", 121 | "ellipse", 122 | "foreignObject", 123 | "g", 124 | "image", 125 | "line", 126 | "linearGradient", 127 | "marker", 128 | "mask", 129 | "path", 130 | "pattern", 131 | "polygon", 132 | "polyline", 133 | "radialGradient", 134 | "rect", 135 | "stop", 136 | "svg", 137 | "text", 138 | "tspan", 139 | ] as const; 140 | -------------------------------------------------------------------------------- /src/directives/index.ts: -------------------------------------------------------------------------------- 1 | import { DirectiveMap } from "../types/directive"; 2 | import { elements } from "./elements"; 3 | import { makeDirective } from "./makeDirective"; 4 | 5 | const directive = {} as DirectiveMap; 6 | 7 | elements.forEach((element) => { 8 | directive[element] = makeDirective(element); 9 | }); 10 | 11 | export default directive; 12 | -------------------------------------------------------------------------------- /src/directives/makeDirective.ts: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { useClassName } from "../hooks/useClassName"; 3 | import { DirectiveProps } from "../types/directive"; 4 | 5 | export const getKey = ( 6 | item: any, 7 | index: number, 8 | dirKey?: string | ((currentItem: any) => string | number) 9 | ): string | number => { 10 | if (!(dirKey && item)) return index; 11 | if (dirKey === "this") return item.toString(); 12 | if (typeof dirKey === "string") 13 | return (item[dirKey] && item[dirKey].toString()) ?? index; 14 | if (typeof dirKey === "function") return dirKey(item); 15 | return index; 16 | }; 17 | 18 | export const makeDirective = ( 19 | component: T 20 | ) => { 21 | type DirectivePropsWithValue = DirectiveProps & 22 | Omit; 23 | 24 | const DirectiveComponent = ({ 25 | dirIf = true, 26 | dirShow = true, 27 | classNameDeps, 28 | dirFor, 29 | dirKey, 30 | children, 31 | style, 32 | dirRef, 33 | className, 34 | ...props 35 | }: DirectivePropsWithValue): React.ReactElement | null => { 36 | const classString = useClassName(className, classNameDeps); 37 | 38 | if (!dirIf) return null; 39 | 40 | const extraProps: Record = { 41 | style: 42 | style || !dirShow 43 | ? { ...style, display: !dirShow ? "none" : style && style.display } 44 | : undefined, 45 | className: classString || undefined, 46 | }; 47 | 48 | return dirFor 49 | ? React.createElement( 50 | React.Fragment, 51 | null, 52 | dirFor.map((item, i) => 53 | React.createElement( 54 | component, 55 | { 56 | ...props, 57 | ...extraProps, 58 | key: getKey(item, i, dirKey), 59 | }, 60 | typeof children === "function" 61 | ? children(item, i) 62 | : (children as React.ReactNode) 63 | ) 64 | ) 65 | ) 66 | : React.createElement( 67 | component, 68 | { ...props, ...extraProps, ref: dirRef }, 69 | children as React.ReactNode 70 | ); 71 | }; 72 | 73 | return DirectiveComponent; 74 | }; 75 | -------------------------------------------------------------------------------- /src/directives/tests/__snapshots__/dir.snapshot.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`anchor element renderes anchor elements correctly Anchor with classNames 1`] = ` 4 | 7 | Some text content 8 | 9 | `; 10 | 11 | exports[`anchor element renderes anchor elements correctly Anchor with dirIf set to false 1`] = `null`; 12 | 13 | exports[`anchor element renderes anchor elements correctly Anchor with dirShow set to false 1`] = ` 14 | 21 | Some text content 22 | 23 | `; 24 | 25 | exports[`anchor element renderes anchor elements correctly Anchor with href and title 1`] = ` 26 | 30 | `; 31 | 32 | exports[`div element renders correctly for div with class generated by useClassName hook 1`] = ` 33 |
36 | `; 37 | 38 | exports[`div element renders correctly for div with className 1`] = ` 39 |
42 | `; 43 | 44 | exports[`div element renders correctly for div with dirFor 1`] = ` 45 | [ 46 |
47 | 1 48 |
, 49 |
50 | 2 51 |
, 52 |
53 | 3 54 |
, 55 | ] 56 | `; 57 | 58 | exports[`div element renders correctly for div with dirIf set to false 1`] = `null`; 59 | 60 | exports[`div element renders correctly for div with dirShow set to false 1`] = ` 61 |
68 | `; 69 | 70 | exports[`div element renders correctly for div with no properties 1`] = `
`; 71 | -------------------------------------------------------------------------------- /src/directives/tests/dir.snapshot.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import directive from ".."; 3 | import { snapshotTest } from "../../helpers/test-helpers"; 4 | 5 | describe("anchor element", () => { 6 | describe("renderes anchor elements correctly", () => { 7 | it("Anchor with href and title", () => { 8 | snapshotTest( 9 | 10 | ); 11 | }); 12 | it("Anchor with dirShow set to false", () => { 13 | snapshotTest( 14 | Some text content 15 | ); 16 | }); 17 | it("Anchor with dirIf set to false", () => { 18 | snapshotTest(Some text content); 19 | }); 20 | 21 | it("Anchor with classNames", () => { 22 | snapshotTest( 23 | 26 | Some text content 27 | 28 | ); 29 | }); 30 | }); 31 | }); 32 | 33 | describe("div element", () => { 34 | it("renders correctly for div with no properties", () => { 35 | snapshotTest(); 36 | }); 37 | 38 | it("renders correctly for div with dirIf set to false", () => { 39 | snapshotTest(); 40 | }); 41 | 42 | it("renders correctly for div with dirShow set to false", () => { 43 | snapshotTest(); 44 | }); 45 | 46 | it("renders correctly for div with className", () => { 47 | snapshotTest(); 48 | }); 49 | 50 | it("renders correctly for div with class generated by useClassName hook", () => { 51 | snapshotTest(); 52 | }); 53 | 54 | it("renders correctly for div with dirFor", () => { 55 | snapshotTest( 56 | {(item) => item} 57 | ); 58 | }); 59 | }); 60 | -------------------------------------------------------------------------------- /src/directives/tests/makeDirective.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { render } from "@testing-library/react"; 3 | import { getKey, makeDirective } from "../makeDirective"; 4 | import { truthyValues, falsyValues } from "../../helpers/test-helpers"; 5 | 6 | describe("getKey()", () => { 7 | it("returns index when dirKey is not defined", () => { 8 | expect(getKey(undefined, 0)).toBe(0); 9 | }); 10 | 11 | it('returns passed item itself when dirKey is "this"', () => { 12 | expect(getKey("item", 0, "this")).toBe("item"); 13 | }); 14 | 15 | it("returns value of dirKey property when dirKey is a string", () => { 16 | const item = { id: 1 }; 17 | expect(getKey(item, 0, "id")).toBe("1"); 18 | }); 19 | 20 | it("returns result of calling the function when dirKey is a function", () => { 21 | const item = { id: 1 }; 22 | const dirKey = jest.fn((i) => i.id); 23 | expect(getKey(item, 0, dirKey)).toBe(1); 24 | expect(dirKey).toHaveBeenCalledWith(item); 25 | }); 26 | 27 | it("returns index if any other type of value is passed as key", () => { 28 | expect(getKey({}, 0, 4 as any)).toBe(0); 29 | }); 30 | }); 31 | 32 | describe("makeDirective", () => { 33 | it("renders a component with the correct class name when dirIf is truthy", () => { 34 | truthyValues.forEach((value) => { 35 | const TestComponent = makeDirective("div"); 36 | const { getByTestId, unmount } = render( 37 | 42 | Test Content 43 | 44 | ); 45 | 46 | const element = getByTestId("test-element"); 47 | expect(element).toHaveClass("test-class"); 48 | unmount(); 49 | }); 50 | }); 51 | 52 | it("does not render a component when dirIf is falsy", () => { 53 | falsyValues.forEach((value) => { 54 | const TestComponent = makeDirective("div"); 55 | const { queryByTestId, unmount } = render( 56 | 57 | Test Content 58 | 59 | ); 60 | 61 | const element = queryByTestId("test-element"); 62 | expect(element).toBeNull(); 63 | unmount(); 64 | }); 65 | }); 66 | 67 | it("shows a component when dirShow is truthy", () => { 68 | truthyValues.forEach((value) => { 69 | const TestComponent = makeDirective("div"); 70 | const { getByTestId, unmount } = render( 71 | 72 | Test Content 73 | 74 | ); 75 | 76 | const element = getByTestId("test-element"); 77 | expect(element).not.toHaveStyle("display: none"); 78 | unmount(); 79 | }); 80 | }); 81 | 82 | it("hides a component when dirShow is falsy", () => { 83 | falsyValues.forEach((value) => { 84 | const TestComponent = makeDirective("div"); 85 | const { getByTestId, unmount } = render( 86 | 87 | Test Content 88 | 89 | ); 90 | 91 | const element = getByTestId("test-element"); 92 | expect(element).toHaveStyle("display: none"); 93 | unmount(); 94 | }); 95 | }); 96 | 97 | it("when other styles exists and hides a component with dirShow set to false", () => { 98 | const TestComponent = makeDirective("div"); 99 | const { getByTestId, unmount } = render( 100 | 105 | Test Content 106 | 107 | ); 108 | 109 | const element = getByTestId("test-element"); 110 | expect(element).toHaveStyle("display: none"); 111 | expect(element).toHaveStyle("text-align: center"); 112 | expect(element).toHaveStyle("font-size: 30px"); 113 | unmount(); 114 | }); 115 | 116 | it("when display style is specified without dirShow set to false", () => { 117 | const TestComponent = makeDirective("div"); 118 | const { getByTestId, unmount } = render( 119 | 123 | Test Content 124 | 125 | ); 126 | const element = getByTestId("test-element"); 127 | expect(element).toHaveStyle("display: flex"); 128 | expect(element).toHaveStyle("margin: 20px"); 129 | unmount(); 130 | }); 131 | 132 | it("dirShow should override style property's display value", () => { 133 | const TestComponent = makeDirective("div"); 134 | const { getByTestId, unmount } = render( 135 | 140 | Test Content 141 | 142 | ); 143 | const element = getByTestId("test-element"); 144 | expect(element).toHaveStyle("display: none"); 145 | unmount(); 146 | }); 147 | 148 | it("renders a component when dirFor is present", () => { 149 | const TestComponent = makeDirective("div"); 150 | const { getAllByTestId, unmount } = render( 151 | 156 | Test Content 157 | 158 | ); 159 | 160 | const elements = getAllByTestId("test-element"); 161 | expect(elements).toHaveLength(2); 162 | unmount(); 163 | }); 164 | 165 | it("renders a component when dirFor is present using dirKey function", () => { 166 | const TestComponent = makeDirective("div"); 167 | const { getAllByTestId, unmount } = render( 168 | value.id} 171 | data-testid="test-element" 172 | > 173 | Test Content 174 | 175 | ); 176 | 177 | const elements = getAllByTestId("test-element"); 178 | expect(elements).toHaveLength(2); 179 | unmount(); 180 | }); 181 | 182 | it("adds the class string to the component", () => { 183 | const TestComponent = makeDirective("div"); 184 | const { getByTestId, unmount } = render( 185 | 190 | Test Content 191 | 192 | ); 193 | 194 | const element = getByTestId("test-element"); 195 | expect(element).toHaveClass("test-class"); 196 | expect(element).toHaveClass("test-class-2"); 197 | unmount(); 198 | }); 199 | }); 200 | -------------------------------------------------------------------------------- /src/helpers/test-helpers.ts: -------------------------------------------------------------------------------- 1 | import { ReactElement } from "react"; 2 | // eslint-disable-next-line import/no-extraneous-dependencies 3 | import renderer from "react-test-renderer"; 4 | 5 | export const snapshotTest = ( 6 | render: ReactElement, 7 | title?: string 8 | ) => { 9 | const tree = renderer.create(render).toJSON(); 10 | expect(tree).toMatchSnapshot(title || ""); 11 | }; 12 | 13 | export const truthyValues = ["value", true, 1, Infinity, -1, -Infinity, {}, []]; 14 | export const falsyValues = ["", false, 0, null]; 15 | export const truthyFalsyMap = truthyValues 16 | .map((value) => 17 | falsyValues.map((falsyValue) => ({ truthy: value, falsy: falsyValue })) 18 | ) 19 | .flat(); 20 | -------------------------------------------------------------------------------- /src/hooks/tests/useClassName.test.ts: -------------------------------------------------------------------------------- 1 | import { renderHook } from "@testing-library/react"; 2 | import { useClassName } from "../useClassName"; 3 | 4 | describe("useClassName", () => { 5 | it("should return empty string if it gets not args", () => { 6 | const { result } = renderHook(() => useClassName()); 7 | expect(result.current).toBe(""); 8 | }); 9 | 10 | describe("When string is received", () => { 11 | it("returns class names passed to it", () => { 12 | const classes = "some class"; 13 | const { result } = renderHook(() => useClassName(classes)); 14 | expect(result.current).toBe("some class"); 15 | }); 16 | }); 17 | 18 | describe("When array is received", () => { 19 | it("returns class names", () => { 20 | const classes = [{ foo: true, bar: false }]; 21 | const { result } = renderHook(() => useClassName(classes)); 22 | expect(result.current).toBe("foo"); 23 | }); 24 | 25 | it("returns class names with other class names", () => { 26 | const classes = ["some-other-class", { foo: true, bar: false }]; 27 | const { result } = renderHook(() => useClassName(classes)); 28 | expect(result.current).toBe("some-other-class foo"); 29 | }); 30 | 31 | it("returns class names with other multiple class names", () => { 32 | const classes = [ 33 | "some-other-class", 34 | { foo: true, bar: false }, 35 | "another-class", 36 | ]; 37 | const { result } = renderHook(() => useClassName(classes)); 38 | expect(result.current).toBe("some-other-class foo another-class"); 39 | }); 40 | }); 41 | 42 | describe("When object is received", () => { 43 | it("returns class names", () => { 44 | const classes = { foo: true, bar: false }; 45 | const { result } = renderHook(() => useClassName(classes)); 46 | expect(result.current).toBe("foo"); 47 | }); 48 | it("returns class names with truthy or falsy values", () => { 49 | const classes = { 50 | foo: 1, 51 | bar: 0, 52 | something: "", 53 | name: null, 54 | blue: true, 55 | yellow: false, 56 | value: undefined, 57 | userName: "jdoe", 58 | }; 59 | const { result } = renderHook(() => useClassName(classes)); 60 | expect(result.current).toBe("foo blue userName"); 61 | }); 62 | it("returns an empty string when no classes are passed", () => { 63 | const classes = {}; 64 | const { result } = renderHook(() => useClassName(classes)); 65 | expect(result.current).toBe(""); 66 | }); 67 | it("returns an empty string when all classes are falsy", () => { 68 | const classes = { 69 | value1: false, 70 | value2: "", 71 | value3: 0, 72 | value4: null, 73 | value5: undefined, 74 | }; 75 | const { result } = renderHook(() => useClassName(classes)); 76 | expect(result.current).toBe(""); 77 | }); 78 | it("returns multiple class names when multiple classes are passed", () => { 79 | const classes = { foo: true, bar: true, something: false, smooth: true }; 80 | const { result } = renderHook(() => useClassName(classes)); 81 | expect(result.current).toBe("foo bar smooth"); 82 | }); 83 | it("returns class names without leading or trailing spaces", () => { 84 | const classes = { foo: true, bar: false }; 85 | const { result } = renderHook(() => useClassName(classes)); 86 | expect(result.current).not.toMatch(/^ | $/); 87 | }); 88 | it("returns class names with a single space between each class", () => { 89 | const classes = { foo: true, bar: true }; 90 | const { result } = renderHook(() => useClassName(classes)); 91 | expect(result.current).toEqual("foo bar"); 92 | }); 93 | 94 | describe("Dependencies and effects", () => { 95 | it("falls back to classes when deps are not provided", () => { 96 | let myClasses = { foo: true, bar: false }; 97 | const { result, rerender } = renderHook( 98 | ({ classes }) => useClassName(classes), 99 | { 100 | initialProps: { 101 | classes: myClasses, 102 | }, 103 | } 104 | ); 105 | expect(result.current).toBe("foo"); 106 | 107 | rerender({ classes: myClasses }); 108 | expect(result.current).toBe("foo"); 109 | 110 | myClasses.bar = true; 111 | rerender({ classes: myClasses }); 112 | expect(result.current).toBe("foo"); // same object in memory, will not cause re-calculation 113 | 114 | myClasses = { foo: true, bar: true }; // same values but different object in memory 115 | rerender({ classes: myClasses }); 116 | expect(result.current).toBe("foo bar"); 117 | }); 118 | it("updates class names on dependency change", () => { 119 | const { result, rerender } = renderHook( 120 | ({ classes, deps }) => useClassName(classes, deps), 121 | { 122 | initialProps: { 123 | classes: { foo: true, bar: false }, 124 | deps: [true, false], 125 | }, 126 | } 127 | ); 128 | expect(result.current).toBe("foo"); 129 | rerender({ classes: { foo: false, bar: true }, deps: [false, true] }); 130 | expect(result.current).toBe("bar"); 131 | }); 132 | }); 133 | }); 134 | }); 135 | -------------------------------------------------------------------------------- /src/hooks/useClassName.ts: -------------------------------------------------------------------------------- 1 | import { useCallback, useEffect, useRef, useState } from "react"; 2 | import { Classes, ClassesDependencies } from "../types/classes"; 3 | 4 | export const useClassName = (classes?: Classes, deps?: ClassesDependencies) => { 5 | const dependencies = deps || [classes]; 6 | 7 | const isMounted = useRef(false); 8 | 9 | const getNames = useCallback((receivedClasses = classes): string => { 10 | if (!receivedClasses) return ""; 11 | if (typeof receivedClasses === "string") return receivedClasses; 12 | if (Array.isArray(receivedClasses)) { 13 | return receivedClasses 14 | .map((value) => (typeof value === "string" ? value : getNames(value))) 15 | .join(" "); 16 | } 17 | return Object.keys(receivedClasses).reduce((acc, v) => { 18 | if (!receivedClasses[v]) return acc; 19 | 20 | return acc ? `${acc} ${v}` : v; 21 | }, ""); 22 | }, []); 23 | 24 | const [classNames, setClassNames] = useState(getNames); 25 | 26 | useEffect(() => { 27 | if (isMounted.current === false) { 28 | // We don't need to recalculate on the first render because useState will do it. 29 | isMounted.current = true; 30 | return; 31 | } 32 | setClassNames(getNames(classes)); 33 | }, dependencies); 34 | 35 | return classNames; 36 | }; 37 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import directive from "./directives"; 2 | 3 | export * from "./components/For"; 4 | 5 | export * from "./components/Switch"; 6 | 7 | export * from "./components/Case"; 8 | 9 | export * from "./components/Default"; 10 | 11 | export * from "./hooks/useClassName"; 12 | 13 | export default directive; 14 | -------------------------------------------------------------------------------- /src/types/classes.ts: -------------------------------------------------------------------------------- 1 | export type Classes = 2 | | Record 3 | | Array> 4 | | string; 5 | 6 | export type ClassesDependencies = Array< 7 | boolean | string | number | bigint | null | undefined 8 | >; 9 | -------------------------------------------------------------------------------- /src/types/directive.ts: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { makeDirective } from "../directives/makeDirective"; 3 | import { Classes, ClassesDependencies } from "./classes"; 4 | 5 | export type Mapper = (currentItem: T, index: number) => React.ReactNode; 6 | 7 | export type DirectiveChildren = Mapper | React.ReactNode; 8 | 9 | export interface DirectiveProps { 10 | dirIf?: any; 11 | dirShow?: any; 12 | className?: Classes; 13 | classNameDeps?: ClassesDependencies; 14 | dirFor?: Array; 15 | dirRef?: React.Ref< 16 | E extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[E] : any 17 | >; 18 | children?: T extends undefined ? React.ReactNode : DirectiveChildren; 19 | dirKey?: T extends undefined 20 | ? never 21 | : string | ((currentItem: T) => string | number); 22 | } 23 | 24 | export type DirectiveMap = { 25 | [Key in keyof JSX.IntrinsicElements]: ReturnType>; 26 | }; 27 | -------------------------------------------------------------------------------- /src/types/for.ts: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export interface ForProps { 4 | each: T[]; 5 | children: (value: T, index: number) => React.ReactNode; 6 | } 7 | -------------------------------------------------------------------------------- /src/types/switch.ts: -------------------------------------------------------------------------------- 1 | import React, { ReactElement } from "react"; 2 | 3 | export interface CaseProps { 4 | when: any | (() => any); 5 | children: React.ReactNode; 6 | } 7 | 8 | export interface DefaultProps { 9 | children: React.ReactNode; 10 | } 11 | 12 | type SwitchChildrenProps = CaseProps | DefaultProps; 13 | 14 | export interface SwitchProps { 15 | children: 16 | | ReactElement 17 | | ReactElement[]; 18 | } 19 | -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src"], 4 | "exclude": ["node_modules"] 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": false, 6 | "skipLibCheck": true, 7 | "outDir": "./dist", 8 | "rootDir": "./src", 9 | "esModuleInterop": true, 10 | "removeComments": true, 11 | "allowSyntheticDefaultImports": true, 12 | "strict": true, 13 | "forceConsistentCasingInFileNames": true, 14 | "module": "CommonJS", 15 | "declaration": true, 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "noEmit": false, 20 | "jsx": "react", 21 | "noFallthroughCasesInSwitch": true 22 | }, 23 | "include": ["src"], 24 | "exclude": [ 25 | "src/**/*.spec.ts", 26 | "src/**/*.spec.tsx", 27 | "src/**/*.test.ts", 28 | "src/**/*.test.tsx", 29 | "node_modules" 30 | ] 31 | } --------------------------------------------------------------------------------