I have this obj, I want to access this p tag content and render it through props. Without dangrouslySetInnerHTML method. What should I've to do?
let content = {
para: `<p>A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.</p>`
}
CodePudding user response:
I would use String.prototype.slice
let content = {
para: `<p>A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.</p>`
}
const text = content.para.slice(3, -4)
console.log(text)
CodePudding user response:
You could extract the text via DOMParser
, then use usual JSX to render that text in a JSX paragraph.
const { useMemo } = React;
let content = {
para: `<p>A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.</p>`,
};
const Example = ({ content }) => {
const paragraph = useMemo(() => {
const parser = new DOMParser();
const doc = parser.parseFromString(content.para, "text/html");
return <p>{doc.querySelector("p").textContent}</p>;
}, [content]);
return (
<div>
Here's the paragraph:
{paragraph}
</div>
);
};
const App = () => {
return <Example content={content} />;
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
I've used useMemo
there because parsing seems like enough work it's worth memoizing and avoiding repeating.
CodePudding user response:
If you want to acheive it in react, without dangrouslySetInnerHTML, it's not possible.
Instead, try this way.
document.querySelector(
'some element',
).innerHTML = `<p>A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.</p>`;
CodePudding user response:
You can create a new element and pass it your content.para
value, after use textContent
on this new element. Like this :
const htmlNode = document.createElement('div')
htmlNode.innerHTML = content.para
const sanitizedContent = htmlNode.textContent