You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.3 KiB
46 lines
1.3 KiB
11 years ago
|
---
|
||
|
id: class-name-manipulation
|
||
|
title: Class Name Manipulation
|
||
|
permalink: class-name-manipulation.html
|
||
11 years ago
|
prev: two-way-binding-helpers.html
|
||
11 years ago
|
next: test-utils.html
|
||
11 years ago
|
---
|
||
|
|
||
|
`classSet()` is a neat utility for easily manipulating the DOM `class` string.
|
||
|
|
||
|
Here's a common scenario and its solution without `classSet()`:
|
||
|
|
||
|
```javascript
|
||
|
// inside some `<Message />` React component
|
||
|
render: function() {
|
||
|
var classString = 'message';
|
||
|
if (this.props.isImportant) {
|
||
|
classString += ' message-important';
|
||
|
}
|
||
|
if (this.props.isRead) {
|
||
|
classString += ' message-read';
|
||
|
}
|
||
|
// 'message message-important message-read'
|
||
11 years ago
|
return <div className={classString}>Great, I'll be there.</div>;
|
||
11 years ago
|
}
|
||
|
```
|
||
|
|
||
|
This can quickly get tedious, as assigning class name strings can be hard to read and error-prone. `classSet()` solves this problem:
|
||
|
|
||
|
```javascript
|
||
|
render: function() {
|
||
11 years ago
|
var cx = React.addons.classSet;
|
||
|
var classes = cx({
|
||
11 years ago
|
'message': true,
|
||
|
'message-important': this.props.isImportant,
|
||
|
'message-read': this.props.isRead
|
||
11 years ago
|
});
|
||
11 years ago
|
// same final string, but much cleaner
|
||
11 years ago
|
return <div className={classes}>Great, I'll be there.</div>;
|
||
11 years ago
|
}
|
||
|
```
|
||
|
|
||
11 years ago
|
When using `classSet()`, pass an object with keys of the CSS class names you might or might not need. Truthy values will result in the key being a part of the resulting string.
|
||
11 years ago
|
|
||
|
No more hacky string concatenations!
|