How to get a React Component reference to change its class using classList?
Above 16.8, using useRef hooks for functional components,
// useRef takes initialValue as param
const fooBarRef = useRef(null);
//DOM Usage
<div className="foo" ref={fooBarRef}>Hello</div>
Usage of reference for useRef after mounting node element,
//Getting node element
const fooBarNode = fooBarRef.current
//Adding class to node element
fooBarNode.classList.add('bar');
Above 16.3, using createRef for class components,
// Creating ref in a constructor
this.fooBarRef = React.createRef();
// DOM usage
<div className="foo" ref={this.fooBarRef}>Hello</div>
Usage of reference for createRef after mounting node element,
//Getting node element
const fooBarNode = this.fooBarRef.current
//Adding class to node element
fooBarNode.classList.add('bar');
Below 16.3, using callBackRef,
// Creating ref in a constructor
this.fooBarRef = null;
this.setFooBarRef = (ref) => {
this.fooBarRef = ref;
}
// DOM usage
<div className="foo" ref={this.setFooBarRef}>Hello</div>
Usage of reference after mounting node element,
//Adding class name
this.fooBarRef.classList.add('bar');
That's because this
is the reference to your class instance, not a DOM element. To access DOM elements (since React uses a virtual DOM) you need to create a reference, i.e:
React.createElement('div', {
ref: 'tabBody'
You can then access it via this.refs.tabBody
You shouldn't pass this reference outside of the class however. Instead you can pass the reference to handleTabClick
when the event happens:
React.createElement('div', {
ref: 'tabBody'
onClick: e => this.props.handleTabClick(e, this.refs.tabBody)
Then you can do:
handleTabClick = function(e, tabBody) {
tabBody.classList.add('tabPreviewComplete');
}
Personally I would change the state though, so that if the component re-renders it has the correct class.
Fiddle: http://jsfiddle.net/ferahl/dpvb1h3y/