Skip to content

Commit

Permalink
Add If Confition Method to ClassNames
Browse files Browse the repository at this point in the history
  • Loading branch information
Christopher Vachon committed Nov 3, 2022
1 parent 8981658 commit 188bc7f
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 1 deletion.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,17 @@ const list = new ClassNames()
// list => "p-1"
```

## If Condition

as of `1.2.0` you use add an If Conditions

```js
const size = "xs";

const list = new ClassNames().if(size === "xs", "rounded-sm", "rounded").list();
// list => "rounded-sm"
```

## Static Methods

- .add() - Alias of `new ClassNames().add()`
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@codevachon/classnames",
"version": "1.1.0",
"version": "1.2.0",
"license": "MIT",
"author": {
"email": "[email protected]",
Expand Down
20 changes: 20 additions & 0 deletions src/ClassNames.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,26 @@ describe("ClassNames", () => {
});
});

describe("if", () => {
const baseClasses = ["Beer", "Banana"];
const isTrue = "true";
const isFalse = "false";

test("Adds the expected values when condition is true", () => {
const condition = true;
expect(new ClassNames(baseClasses).if(condition, isTrue, isFalse).list()).toContain(
isTrue
);
});

test("Adds the expected values when condition is false", () => {
const condition = false;
expect(new ClassNames(baseClasses).if(condition, isTrue, isFalse).list()).toContain(
isFalse
);
});
});

describe("static isClassNames method", () => {
test("returns true if value is an instance of ClassNames", () => {
const value = ClassNames.add("me");
Expand Down
26 changes: 26 additions & 0 deletions src/ClassNames.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,32 @@ class ClassNames {
return this;
}

/**
* Conditionally Added Classes
*
* ```ts
* new ClassNames().if(disabled === true, "bg-gray-100", "bg-sky-700").list();
* ```
*
* @param condition The If Condition
* @param isTrue Values to add if the Condition is True
* @param isFalse Values to add of the Condition is False
* @returns this instance
*/
public if(
condition: boolean,
isTrue: ClassNameAddValue,
isFalse: ClassNameAddValue = ""
): this {
if (condition) {
this.add(isTrue);
} else {
this.add(isFalse);
}

return this;
}

/**
* Static accessor to add ClassNames
*
Expand Down

0 comments on commit 188bc7f

Please sign in to comment.