Search code examples
reactjschatbot

How to navigate to a new page/Component ? react chatbot


I have been trying to create a react-based chatbot, in that if a user presses an option/button from the chatbot I want to display a component outside of the chatbot and on the same page.

this is my sample chatbot Code :


     {
                  id: "summary-end-graph",
                  asMessage: false,
    
                  component: <Calculators/>,
                  
                  trigger: "summary-ends-last",
                  waitAction : true,
                  delay: 1300,
    
                },

I have mentioned here as Calculators is a different component

Sample code of the Calculators component

    class Calculators extends Component {
      constructor(props) {
        super(props);  
        const { steps } = this.props;
        const { salaryanswer, rate } = steps;
    ................

When the user clicks on an option inside the chatbot, the calculators component should come out of the chatbot. How can I do this?


Solution

  • You can call the component outside the chatbot first and add conditional rendering like this:

    <ChatBot optionClicked={this.toggleOption} />
    {
      optionClicked ?
        <Calculators/> :
        <div></div>
    }
    

    before that you would set up the optionClicked state in

        constructor(props) {
        super(props);
        this.state = {optionClicked : false};
        }
    

    and a function toggleOption

    toggleOption = () => {
        this.setState({ optionClicked: !optionClicked })
      }
    

    Then in the chatbot you would click the button:

        <button onClick={() => this.props.optionClicked()}>Option</button>
    

    Now clicking the button should toggle the component outside the chatbot.