|
| 1 | +--- |
| 2 | +id: class-name-manipulation |
| 3 | +title: Class Name Manipulation |
| 4 | +layout: docs |
| 5 | +permalink: class-name-manipulation.html |
| 6 | +prev: form-input-binding-sugar.html |
| 7 | +next: examples.html |
| 8 | +--- |
| 9 | + |
| 10 | +`classSet()` is a neat utility for easily manipulating the DOM `class` string. |
| 11 | + |
| 12 | +Here's a common scenario and its solution without `classSet()`: |
| 13 | + |
| 14 | +```javascript |
| 15 | +// inside some `<Message />` React component |
| 16 | +render: function() { |
| 17 | + var classString = 'message'; |
| 18 | + if (this.props.isImportant) { |
| 19 | + classString += ' message-important'; |
| 20 | + } |
| 21 | + if (this.props.isRead) { |
| 22 | + classString += ' message-read'; |
| 23 | + } |
| 24 | + // 'message message-important message-read' |
| 25 | + return <div className={classString}>Great, I'll be there.</div> |
| 26 | +} |
| 27 | +``` |
| 28 | +
|
| 29 | +This can quickly get tedious, as assigning class name strings can be hard to read and error-prone. `classSet()` solves this problem: |
| 30 | +
|
| 31 | +```javascript |
| 32 | +render: function() { |
| 33 | + var classSet = React.addons.classSet; |
| 34 | + var classes = { |
| 35 | + 'message': true, |
| 36 | + 'message-important': this.props.isImportant, |
| 37 | + 'message-read': this.props.isRead |
| 38 | + } |
| 39 | + // same final string, but much cleaner |
| 40 | + return <div className={classSet(classes)}>Great, I'll be there.</div> |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +Pass to `classSet()` an object, whose key is the CSS class name you might or might not need, and whose value is a boolean (or anything that converts to it) that indicates whether the key should be present in the final class string. |
| 45 | + |
| 46 | +No more hacky string concatenations! |
0 commit comments