score:394
You can use dangerouslySetInnerHTML, e.g.
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
);
}
score:-5
You can also include this HTML in ReactDOM like this:
var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);
ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));
Here are two links link and link2 from React documentation which could be helpful.
score:-2
If anyone else still lands here. With ES6 you can create your html variable like so:
render(){
var thisIsMyCopy = (
<p>copy copy copy <strong>strong copy</strong></p>
);
return(
<div>
{thisIsMyCopy}
</div>
)
}
score:1
Try Fragment, if you don't want any of above.
In your case, we can write
import React, {useState, Fragment} from 'react'
const thisIsMyCopy = Fragment('<p>copy copy copy <strong>strong copy</strong></p>')
render: function() {
return (
<div className="content">{thisIsMyCopy}</div>
);
}
If you using hook want to set it in a state somewhere with any condition
const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment><p>copy copy copy <strong>strong copy</strong></p></Fragment>);
score:6
To avoid linter errors, I use it like this:
render() {
const props = {
dangerouslySetInnerHTML: { __html: '<br/>' },
};
return (
<div {...props}></div>
);
}
score:6
You don't need any special library or "dangerous" attribute. You can just use React Refs to manipulate the DOM:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.divRef = React.createRef();
this.myHTML = "<p>Hello World!</p>"
}
componentDidMount() {
this.divRef.current.innerHTML = this.myHTML;
}
render() {
return (
<div ref={this.divRef}></div>
);
}
}
A working sample can be found here:
score:7
import { Fragment } from 'react' // react version > 16.0
var thisIsMyCopy = (
<Fragment>
<p>copy copy copy
<strong>strong copy</strong>
</p>
</Fragment>
)
By using '' the sets the value to a string and React has no way of knowing that it is a HTML element. You can do the following to let React know it is a HTML element -
- Remove the
''
and it would work - Use
<Fragment>
to return a HTML element.
score:59
By using ''
you are making it to a string. Use without inverted commas it will work fine.
const App = () => {
const span = <span> whatever your string </span>
const dynamicString = "Hehe";
const dynamicStringSpan = <span> {`${dynamicString}`} </span>
return (
<div>
{span}
{dynamicStringSpan}
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
score:63
dangerouslySetInnerHTML has many disadvantage because it set inside the tag.
I suggest you to use some react wrapper like i found one here on npm for this purpose. html-react-parser does the same job.
import Parser from 'html-react-parser';
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
return (
<div className="content">{Parser(thisIsMyCopy)}</div>
);
}
Very Simple :)
score:135
Note that dangerouslySetInnerHTML
can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.
It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.
Example:
import DOMPurify from 'dompurify'
const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
);
}
Source: stackoverflow.com
Related Query
- Insert HTML with React Variable Statements (JSX)
- Insert React component into a String variable with html content
- Insert custom React component into a String variable with html content
- ternary operator in jsx to include html with react
- JSX with a HTML tag from a variable
- Store multiple html elements in variable with React
- React rendering variable with html characters escaped
- React JSX with component in variable does not sync props
- ReactJs - Converting raw HTML with nested React Component into JSX
- If statements inside JSX with React
- Wordpress Gutenberg React – render variable with HTML
- Insert React env variable into HTML script tag
- Insert React variable as attribute in html tag
- How to dynamically insert a local variable in to a react JSX map function?
- Insert HTML element into DOM with React
- How to parse html string to JSX client side with variable and function call
- HTML Element with React variable does not display ASCII
- How to insert React state value into HTML Template with predefined value in Sun Editor?
- React render html from a string with a dynamic variable
- Mapping components with variable props not rendering from JSX to DOM, React
- Grouping variable number of elements with React / JSX
- How do I change a variable in a for loop with a onclick ? React jsx file
- Comparing React JSX to generated HTML with Jest/Enzyme
- forEach() in React JSX does not output any HTML
- Can I use jsx without React to inline HTML in script?
- Formatting code with <pre> tag in React and JSX
- Using onBlur with JSX and React
- How do you reference a process.env variable in HTML <script src="" ? React
- add raw HTML with <script> inside Gatsby React page
- Convert react JSX object to HTML
More Query from same tag
- Local JSON file is not parsing in React
- How can i push array in matrix vertically?
- React function is called twice instead of once
- React Redux - very slow onChange
- navigating from a tab screen to a stack screen
- Style JSX is not working properly with @media-query in NextJS
- React: this.state vs this.setState
- Replace the array of elements using another array of elements if its have both common value
- Writing a function inside a functional component in react
- unable to display response from post request in react
- Need to put a scrollable Div inside a container with relative position and scrollable should not affect the main div
- 'npx create-react-app [name] --template typescript' error
- React Bootstrap OverlayTrigger and Tooltip error
- How to wait for event request of Rudderstack JavaScript SDK?
- Throws cannot use 'in' operator to search for 'validateStatus' error
- Client side state is not hydrated from server on page reload
- Why useEffect hook runs before the DOM is loaded?
- How to convert CSS with properties to MaterialUI Styles in ReactJS
- How to join two arrays in a map function?
- How can I wait for the value from localStorage?
- How to pass multiple arguments through React Context (from Consumer to Provider)?
- Material UI card content height/cardcontent fixed to bottom
- React component re renders to it's initial state automatically
- my data is not adding in to my firebase real time database
- input pattern='[a-zA-Z]' is not working in React application
- CRA 2.0 How to setup proxy in React?
- Can I change a Typescript required prop to not required if another optional prop is used?
- Create modal in react-redux using stateless functional components
- MUI 5 sx not working correctly with typescript?
- How do I persist my theme to localStorage in NextJs?