Search code examples
javascriptreactjsmaterial-uidialogflow-esapi-ai

Toggling a Dialogflow Chat Window by clicking on a Material-UI Floating Action Button in ReactJS


In the below code snippet, I am trying to toggle <ChatWidget />, which is a Dialogflow Chat Window, when a user clicks on the <FloatingActionButton/> with the default state set to false. When clicked on the Material-UI Floating Action Button, it does not toggle the state to true. I am using Material UI v1.0.0-beta34. Here is the code snippet:

import React, { Component } from 'react';
import ChatWidget from './ChatWidget';
import FloatingActionButton from './Fab';
class ChatComponent extends Component {
constructor( props ){
  super( props )
  this.state = { show : false };
  this.toggleDiv = this.toggleDiv.bind(this)
 }
toggleDiv = () => {
  const { show } = this.state;
  this.setState( { show : !show } )
}
render() {
  return (
  <div>
    <div>
      { this.state.show && <ChatWidget /> }
    </div>
  <FloatingActionButton onClick={ this.toggleDiv } />
  </div>
   );
  }
 }
 export default ChatComponent;

The page without clicking the FAB looks like this:

default state

The desired functionality when the FAB is clicked is shown below:

desired functionality on click of FAB when state is toggled to true

Any help or suggestions regarding the proper way to toggle the <ChatWidget /> on clicking the <FloatingActionButton /> is much appreciated.


Solution

  • I found the solution. The problem was <FloatingActionButton /> is a custom component that I made. If I have to make the FloatingActionButton respond to clicks, I have to add the OnClick property in the Material UI <Button/> component itself. The modified code that works:

    import React, { Component } from 'react';
    import ChatWidget from './ChatWidget';
    import Button from 'material-ui/Button';
    const style = {
     margin: 0,
     top: 'auto',
     right: 20,
     bottom: 20,
     left: 'auto',
     position: 'fixed',
     backgroundColor:'#E65100',
     color:'#FFFFFF',
    };
    
      class ChatComponent extends Component {
       constructor( props ){
        super( props )
        this.state = { show : false };
    
        this.toggleDiv = this.toggleDiv.bind(this)
       }
    
       toggleDiv = () => {
        const { show } = this.state;
        this.setState( { show : !show } )
      }
      render() {
        return (
        <div>
          <div>
           { this.state.show && <ChatWidget /> }
          </div>
         <Button variant="fab" aria-label="add" style={style} onClick={ 
          this.toggleDiv } >
        <i class="fas fa-comment"></i>
         </Button>
         </div>
         );
       }
      }
      export default ChatComponent;