Reputation: 165
I created tabs in react and and now on click I have to change the class of the tabs the tabs classes may be as follows:
1:active
2:previousActive
3:alreadySelected
On click of a tab class become active
and check whether it is selected before or not using alreadySelected
class and active
class from the last active tab is remove and if it is not alreadySelected
then add alreadySelected
.
Code of one tab in react:
var TabBody = React.createClass({
getInitialState: function() {
return {
class: 'tabBody tab activeTab'
}
},
render: function() {
a.tabBody = this;
return (React.createElement('div', {
className: this.state.class,
ref: 'body',
onClick: handleTabClick
},
React.createElement('span', {}, "Body"))
);
}
});
In order to change the class of the tabs I am doing in two ways and want to know which is effective. Code style one:
var bodyClass = (a.tabBody.state.class).split(' ');
var sleeveClass = (a.tabSleeve.state.class).split(' ');
var neckClass = (a.tabNeck.state.class).split(' ');
if (data === 'tabBody') {
bodyClass.push('activeTab');
var str1 = program.arrayToString(bodyClass);
Interfaces.tabBody.setState({
class: str1
});
}
Code Style 2
a.tabBody.refs.body.classList.remove('activeTab');
a.tabBody.refs.body.classList.add('tabPreviewComplete');
a.tabSleeve.refs.body.classList.add('activeTab');
Which style is good for doing this and why?
Upvotes: 3
Views: 3455
Reputation: 618
ref means you are using the actual DOM and setState means you are saying to react that please update the specific attribute of the component. every thing is maintain by react.
On the other hand if you use refs it means you are doing every thing your own and react have no concern to your attributes and properties you are updating.
Upvotes: 0
Reputation: 14101
The point of react is that you do not need to/ should not update DOM directly. The idea behind react is that you render react components (virtual DOM), and that you let react figure out if and how to update DOM.
Changing classes using refs is a very risky strategy: Your component's state is then no longer in sync with actual DOM, which could bring you into debugging nightmares later on. So I would pose that Code Style 2 (even though it works) violates react principles. One of the few exceptions for using refs, is to add a listener to a DOM component after it is mounted.
The react way is to put the classNames in state.
And do a setState()
to update.
And let react do the DOM update,
which is very likely to be way faster, cleaner, and easier to maintain than getting refs, and changing classNames.
Upvotes: 8