I am building snippet block to add code inside <pre><code>
tag.
However, when the code viewed - the <pre>
tag is having unnecessary tag.
My snippet block react code
edit({ attributes, setAttributes, isSelected }) {
const { text } = attributes;
return (
<Fragment>
<RichText
identifier="text"
value={text}
placeholder={__('Text')}
onChange={nextText => {
setAttributes({
text: nextText,
});
}}
/>
</Fragment>
);
},
save({ attributes }) {
const { text } = attributes;
return (
<pre>
{text && (<code>{text}</code> )}
</pre>
);
},
};
The code inserted from gutenberg editor - for testing.
Python program to illustrate destructor
class Employee:
Initializing
def __init__(self):
print('Employee created.')
Deleting (Calling destructor)
def __del__(self): print('Destructor called, Employee deleted.')
obj = Employee()
del obj
But the above test snippet is pulled as:
the rendered snippet block without line break and
tag.
The issue originated from HTML storing. the issue coming from wrong formatting during storing.
How to resolve this. So that the code can be stored and viewed inside the <pre><code>
block with line break, without unnecessary class in <pre>
tag
React will by default escape your HTML to prevent cross site scripting attacks (XSS) to your website. If you want to post plain HTML you should use the dangerouslySetInnerHTML prop on your HTML element and pass the innerHTML
as an object where the key is __html
and the value is the HTML you would like to post.
dangerouslySetInnerHTML
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.
So you would write your code as:
<pre>
{text && ( <code dangerouslySetInnerHTML={{ __html: text}} /> )}
</pre>
In regards to the wp-block-example-snippet
class that gets automatically added to your <pre>
element, you can remove it by adding this to your theme's function.php file in wordpress:
function wpassist_remove_block_library_css(){
wp_dequeue_style( 'wp-block-library' );
}
add_action( 'wp_enqueue_scripts', 'wpassist_remove_block_library_css' );
Although note that this will remove the Gutenberg's automatically added CSS file from your website:
<link rel='stylesheet' id='wp-block-library-css' href='https://nextseasontv.com/wp-includes/css/dist/block-library/style.min.css' type='text/css' media='all' />
Gutenberg uses these CSS libraries to manage blocks on your site’s frontend. If you are not using them you can remove them by the above instruction.