conversational-form
conversational-form copied to clipboard
Not working when using React Hooks ?
I can't figure out how to make this library work with React Hooks. It doesn't seem to append children to my div element.
To reproduce my "bug": 1 - Create a new React project using Create React App using the TypeScript template 2 - Paste my App component :
import React, { useRef } from "react";
import { ConversationalForm } from "conversational-form";
export const App = () => {
const formFields = [
{
tag: "input",
type: "text",
name: "firstname",
"cf-questions": "What is your firstname?",
},
{
tag: "input",
type: "text",
name: "lastname",
"cf-questions": "What is your lastname?",
},
];
let cf: any;
const elem = useRef<HTMLDivElement>(null);
const submitCallback = () => {
var formDataSerialized = cf.getFormData(true);
console.log("Formdata, obj:", formDataSerialized);
cf.addRobotChatResponse(
"You are done. Check the dev console for form data output."
);
};
useRef(() => {
const cf = ConversationalForm.startTheConversation({
options: {
submitCallback: submitCallback,
preventAutoFocus: true,
// loadExternalStyleSheet: false
},
tags: formFields,
});
elem.current!.appendChild(cf.el);
});
return (
<div style={{ height: "100vh" }}>
<div ref={elem} />
</div>
);
};
Any idea why it doesn't work?
Hello,
I have a working example with react hooks, from my tests the conversational-form library has any bugs related to hooks.
https://react-conversational-form-example-oaijb2.stackblitz.io
@jenssogaard maybe it would be nice to add it to the examples in the docs?
import React, {useEffect, useRef} from 'react';
import { ConversationalForm } from 'conversational-form';
export default function MyForm() {
let cf = null;
const ref = useRef(null);
const formFields = [
{
'tag': 'input',
'type': 'text',
'name': 'firstname',
'cf-questions': 'What is your firstname?'
},
{
'tag': 'input',
'type': 'text',
'name': 'lastname',
'cf-questions': 'What is your lastname?'
}
];
useEffect(function mount() {
cf = ConversationalForm.startTheConversation({
options: {
theme: 'blue',
submitCallback: submitCallback,
preventAutoFocus: true,
// loadExternalStyleSheet: false
},
tags: formFields,
});
ref.current.appendChild(cf.el);
return function unMount(){
cf.remove();
};
}, []);
function submitCallback() {
var formDataSerialized = cf.getFormData(true);
console.log("Formdata, obj:", formDataSerialized);
cf.addRobotChatResponse("You are done. Check the dev console for form data output.")
}
return (
<div>
<div ref={ref} />
</div>
);
}