I have been testing with SunEditor since I want to pre-load an HTML text stored in DB and let users modify it if necessary. I'm passing a ref variable from parent so when the submit button is clicked he could get the value and save modificacions. setContents is just working sometimes. When I save the project and is compiled again text appeared. But if I use the app or refresh the window text dissapear. I have checked that the variable still has the value. I'm new to React and I'm not sure If I'm doing it wrong or just suneditor-react failing. Can you help me?
Here is my code:
export const TranslationArea = React.forwardRef((props, ref) =>{
const handleEditorChange = (value) => {
console.log(value);
ref.current= value;
}
const handleClick = () => {
console.log(ref.current);
}
return(
<div>
<h2>{props.title}</h2>
<SunEditor
autoFocus={true}
width="100%"
height="150px"
setOptions={{
buttonList: [
// default
['undo', 'redo'],
['bold', 'underline', 'italic', 'list'],
['table', 'link', 'image'],
['fullScreen']
]
}}
setContents={props.content}
onChange={handleEditorChange}
/>
<div>{props.content}</div>
<button onClick={handleClick}>Content</button>
</div>
);
});
Here is the screenshot with content properly loaded inside SunEditor div (only when compiling project):
If I refresh the page or navigate to the same link...
I have displayed a div with the same props.content just to check that fowardRef is working. Why setContents is now working? I have inspect with React tools and the property is loaded:
Any idea?
If all you need to access is the value, let's pass down a callback instead. We'll call it
onSumbit
and it will be a function which takes thestring
value from theSunEditor
component.In order to have access to the current edited value, I am using a local state in the
TranslationArea
component and updating that state through the editor'sonChange
method. Then when the submit button is clicked, I callonSubmit
with the value ofcontent
from the local state. (There might be another way to do this but I'm not familiar with SunEditor).The
TranslationArea
component looks like this:I tested it in my CodeSandbox by giving it an
onSubmit
function which logs the submitted content, but you can do whatever you need to with it.CodeSandbox Link