Highlight hovered column and row in ReactJS
We got a new task at work: create a board view for our team! Even though we are EmberJS fans, we chose ReactJS for this task to learn a new JavaScript library.
In the first version, I created a simple board view.
Our HTML structure wraps the rows together, so highlighting the row is very simple with CSS:
1
2
3
.board-component-body-row:hover {
background: #E0F2F1;
}
For the same reason we cannot have a wrapper around the columns too. In our case the first column will always be the name and the rest will be different statuses. We add a class for every element in a row:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
getClassName(){
const defaultClass = "board-component-body-row-elementbox "
if (this.props.name !== undefined) {
return defaultClass + "name";
}
return defaultClass + "status-" + this.props.statusId;
}
renderPostits(){
return this.props.postits.map(
(postit) =>
<BoardPostit key={postit.id} postit={postit} />
);
}
render() {
return (
<div className={this.getClassName()} key={this.props.statusId} >
{this.props.name !== undefined ? this.props.name : this.renderPostits()}
</div>
);
}
But this is not enough for us. We have to know when we enter and leave by hovering over an element. I added an onMouseEnter
and an onMouseLeave
event listener using the JavaScript arrow function syntax as that gives me access to the this
. With a little help of jQuery I add or remove a simple class hovering
depending on when the mouse enters or leaves the area of the element. This jQuery snippet will apply hovering class on every element that has the same classes (in our case the same status classes): which is every element in the same column.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
getClassName(){
const defaultClass = "board-component-body-row-elementbox "
if (this.props.name !== undefined) {
return defaultClass + "name";
}
return defaultClass + "status-" + this.props.statusId;
}
onMouseEnter = (event) => {
const classes = "." + this.getClassName().split(' ').join('.');
$(classes).addClass('hovering');
}
onMouseLeave = (event) => {
const classes = "." + this.getClassName().split(' ').join('.');
$(classes).removeClass('hovering');
}
renderPostits(){
return this.props.postits.map(
(postit) =>
<BoardPostit key={postit.id} postit={postit} />
);
}
render() {
return (
<div className={this.getClassName()} key={this.props.statusId}
onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}>
{this.props.name !== undefined ? this.props.name : this.renderPostits()}
</div>
);
}
I applied a new CSS rule (using SASS). This only applies the background color on the column that are statuses and not names.
1
2
3
4
5
6
7
.board-component-body-row-elementbox {
&:not(.name) {
&.hovering {
background: #E0F2F1;
}
}
}
The codebase can be found on GitHub.