Who do I receive this error in console when running my program?
Uncaught TypeError: Cannot read properties of undefined (reading 'value') on react-quill
Why can't I get the text from the text editor that made using react-quill? But if I'm using a basic input tag text type, it can get the text from the input.
import './App.css';
import {useState, useEffect, useRef} from "react";
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import axios from "axios";
function App() {
const [userValue, setUserValue] = useState('');
const [suggestionPart, setSuggestionPart] = useState('');
const inputRef = useRef();
const userValueRef = useRef();
userValueRef.current = userValue;
function handleUserInputChange(e) {
const newUserValue = e.target.value;
const diff = newUserValue.substr(userValue.length);
if (suggestionPart.indexOf(diff) === 0) {
setSuggestionPart(suggestionPart.substr(diff.length));
} else {
setSuggestionPart('');
}
setUserValue(newUserValue);
}
function findSuggestionFor(phrase) {
return new Promise((resolve, reject) => {
axios.get('http://universities.hipolabs.com/search?name='+phrase)
.then(result => {
const found = result.data.find(university => university.name.indexOf(phrase) === 0);
if (found) {
resolve(found.name);
} else {
reject();
}
})
});
}
useEffect(() => {
if (userValue.length > 0) {
findSuggestionFor(userValue)
.then(universityName => {
const stillFits = universityName.indexOf(userValueRef.current) === 0;
if (stillFits) {
setSuggestionPart(universityName.substr(userValueRef.current.length));
} else {
setSuggestionPart('');
}
})
.catch(() => {
setSuggestionPart('');
});
} else {
setSuggestionPart('');
}
}, [userValue]);
useEffect(() => {
console.log(userValueRef.current);
inputRef.current.selectionStart = userValueRef.current.length;
inputRef.current.selectionEnd = userValueRef.current.length + suggestionPart.length;
}, [suggestionPart]);
return (
<ReactQuill
placeholder="testing..."
modules={App.modules}
formats={App.formats}
ref={inputRef}
onChange={e => handleUserInputChange(e)}
value={userValue+suggestionPart}
/>
);
}
export default App;
The component you're using isn't a native HTML element and does not emit a native change event.
From the react-quill documentation...
onChange(content, delta, source, editor)
: Called back with the new contents of the editor after change.
Your change handler should be defined like this
function handleUserInputChange(newUserValue) {
const diff = newUserValue.substr(userValue.length);
// etc
}
and bind it to the component props like this
<ReactQuill
placeholder="testing..."
modules={App.modules}
formats={App.formats}
ref={inputRef}
onChange={handleUserInputChange}
value={userValue+suggestionPart}
/>