I’m trying to find the best way to add some html (strong, span) and css styling via props.
So my component could be reusable with different input and I could format it directly via the props.
I want the words with $* *$ to be rendered in strong tag but I’m afraid about injections
<HeroCourse title="La $*grammaire*$ de l’espagnol"
description="Toutes les $**règles**$ de grammaire pour apprendre à lire, écrire et parler espagnol"
/>
I have this code but I know it’s not the right way.
import Input from './../UI/buttons/Input';
import DOMPurify from 'dompurify';
import styles from "./HeroCourse.module.css";
function parseCustomSyntax(text) {
// Replace occurrences of *text* with <span style="color: red;">text</span>
text = text.replace(/*([^*]*)*/g, '<span style="color: red;">$1</span>');
// Replace occurrences of **text** with <strong>text</strong>
text = text.replace(/**([^*]*)**/g, '<strong>$1</strong>');
// Replace occurrences of $*text*$ with <strong style="color: red;">text</strong>
text = text.replace(/$*([^$]*)*$/g, '<strong style="color: red;">$1</strong>');
// Replace occurrences of $**text**$ with <span>$1</span>
text = text.replace(/$**([^$]*)**$/g, '<span>$1</span>');
return text;
}
function HeroCourse({ title, description, inputProps }) {
const formattedTitle = parseCustomSyntax(title);
const formattedDescription = parseCustomSyntax(description);
return (
<div className={styles["hero-course-container"]}>
<div className={styles["hero-course"]}>
<h2 dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(formattedTitle) }} />
<p dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(formattedDescription) }} />
<Input {...inputProps} />
</div>
</div>
);
}
export default HeroCourse;
Thank you everyone for helping me !