Search code examples
javascriptfacebookreactjs

How to get a React Component reference to change its class using classList?


I have create a React Component using the following code. In this i am creating tab and added the class and storing its reference to in a global namespace Interface for further processing.

var TabBody = React.createClass({
  getInitialState: function() {
    return {
      class: 'tabBody tab activeTab'
    }
  },
  render: function() {
    Interfaces.tabBody = this;
    tabSelectionInfo.tabBody = this;
    return (
      React.createElement('div', {
          className: this.state.class,
          onClick: handleTabClick
        },
        React.createElement('span', {}, "Body"))
    );
  }
});

now using the following function, To add a class to the above component and console is showing an error undefined. how i store the refrance of this component in order to change its class later.

handleTabClick = function() {
  Interfaces.tabBody.classList.add('tabPreviewComplete');
}

Solution

  • As you have specified in your code that your class name is used using a state variable named 'class' containing the value 'tabBody tab activeTab'

    className: this.state.class,
    

    Thats why you must have to use setState() method to change your className. As you have the reference to your class instance in global namespace named 'Interface.tabBody' which can be used to set your className by calling setState() e.g

    Interface.tabBody.setState({class: 'tabBody tab activeTab disabled'});
    

    This method is used when you want to access class instance outside of the React.

    if you are using handleclick() in your react then you can use the following code

    handleTabClick = function() {
      this.setState({class: 'tabBody tab activeTab disabled'});
    }
    

    By calling setState() the React will detect changes and re-renders component.