Yesterday I had the case that I wanted to save in Gutenberg in the “save” function, a variable that I had prepared by previous inputs as HTML. This variable has contained <br> tags and these were saved as plain text.
Since i work in Gutenberg with React, I have googled some and came to the solution with dangerouslySetInnerHTML . This feature is described in the React documentation as follows:
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.
React Documentation – DOM Elements
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
My solution
I still used this method because it’s not for output but just for storing the variable. This danger would be effect if you were to use this function in the output in the frontend and did not make any security arrangements.
I hope you understand that I show only part of the save section.
save: ( props ) => {
const { attributes: { product_description }} = props;
return <span dangerouslySetInnerHTML={{__html: product_description}}></span>;
}
Conclusion
That was the quick solution I found and I have tested it successfully. If you think that this is not necessarily the best solution, feel free to send me your suggestion via e-mail .
Otherwise, I hope to have helped you further. Have a nice day!